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.
Example:
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
// 0ms, 100%
class Solution {
public:
int numWays(int n, int k) {
if (n == 0 || k == 0)
return 0;
if (n < 2)
return k;
int diffs = k*(k-1); // first two paint differently
int sames = k; // first two paint the same
for (int i = 3; i <= n; i++) {
auto old_diffs = diffs;
diffs = (k-1)*(diffs + sames); // paint differntly with previous
sames = old_diffs; // paint same
}
return sames + diffs;
}
};
// 4ms, 89%
class Solution {
private:
int numWays1(int n, int k, bool isFree, vector<vector<int>>& dp) {
if (n == 0)
return 1;
if (dp[n][isFree] >= 0) {
return dp[n][isFree];
}
int r = (k-1)*numWays1(n-1, k, true, dp);
if (isFree) {
r += numWays1(n-1, k, false, dp);
}
dp[n][isFree] = r;
return r;
}
public:
int numWays(int n, int k) {
if (k == 0 || n == 0)
return 0;
if (n == 1) return k;
if (k == 1) {
if (n <= 2) return 1;
return 0;
}
vector<vector<int>> dp(n+1, {-1,-1});
int r = k*(k-1)*numWays1(n-2, k, true, dp);
if (n >= 2) {
r += k*numWays1(n-2, k, false, dp);
}
return r;
}
};