Problem
There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.
Example
Given n=3, k=2 return 6
post 1, post 2, post 3
way1 0 0 1
way2 0 1 0
way3 0 1 1
way4 1 0 0
way5 1 0 1
way6 1 1 0
Note
DP
Solution
class Solution {
public int numWays(int n, int k) {
if (n == 0) return 0;
if (n == 1) return k;
int[] same = new int[n];
int[] diff = new int[n];
same[0] = k;
same[1] = k;
diff[0] = k;
diff[1] = k*(k-1);
for (int i = 2; i < n; i++) {
same[i] = diff[i-1];
diff[i] = (k-1)*same[i-1]+(k-1)*diff[i-1];
}
return same[n-1]+diff[n-1];
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。