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.
解法1: DP with O(N) time and O(1) space
经典DP, dp[i]表示第i根柱子可能paint的方法数量。考虑三根柱子,如果第i根柱子和第i - 1根一样,那么一定和第i-2根不一样,所以这种情况有k - 1个颜色可选。同理,如果i和第i -2根一样,
那必然和第i - 1根不一样,也是k - 1种颜色可选。
dp[i] = (k - 1) * (dp[i -1] + dp[i - 2])
|
|