276_Paint_Fence
Paint Fence
Difficulty Easy
tags DP
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.
思路:
注意观察即可。
solution 1
class Solution {
public:
int numWays(int n, int k) {
if (n < 2) return n*k;
int dp[2] = {k, k*k};
int c = 2;
while (c++ < n) {
int p = dp[1];
dp[1] = (dp[0] + dp[1]) * (k - 1);
dp[0] = p;
}
return dp[1];
}
};

浙公网安备 33010602011771号