题目描述
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.
样例
Input: n = 3, k = 2
Output: 6
Explanation: Take c1 as color 1, c2 as color 2. All possible ways are:
post1 post2 post3
----- ----- ----- -----
1 c1 c1 c2
2 c1 c2 c1
3 c1 c2 c2
4 c2 c1 c1
5 c2 c1 c2
6 c2 c2 c1
算法1
(DP from states) $O(n^2)$
Calculate two states:
- paint with same color
- paint with different color
Update states:
-
diff: k - 1 kinds of paint from the same states, k - 1 kinds of paints from the old diff states
diff = same * (k - 1) + (old)diff * (k - 1) -
same: exactly the same ways from the old diff ways, it can’t have the old same because we can only have 2 fence at the same color
same = diff
时间复杂度
O(n)
JAVA 代码
public int numWays(int n, int k) {
if (n == 0) return 0;
if (n == 1) return k;
int same = k;
int diff = k * (k - 1);
for (int i = 2; i < n; i++) {
int s = same;
int d = diff;
diff = s * (k - 1) + d * (k - 1);
same = d;
}
return same + diff;
}