276. Paint Fence
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.
Note:
n and k are non-negative integers.
S:DP 滚动数组 O(n)
dp[i][0]表示第i个fence与前一个刷不同颜色时可得到的paint ways,dp[i][1]表示第i个fence与前一个刷相同颜色时可得到的paint ways
dp[i]只与dp[i-1]有关,可用滚动数组优化存储
int numWays(int n, int k) {
if (n == 0) return 0;
vector<vector<int>> dp(2, vector<int>(2, 0));
dp[0][0] = k;
for (int i = 1; i < n; ++i) {
dp[i % 2][0] = (k - 1) * (dp[(i - 1) % 2][0] + dp[(i - 1) % 2][1]);
dp[i % 2][1] = dp[(i - 1) % 2][0];
}
return dp[(n - 1) % 2][0] + dp[(n - 1) % 2][1];
}