Input: n =3, k =2Output: 6Explanation: All the possibilities are shown.Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color.
Use dynamic programming to count the number of ways to paint the fence such that no more than two adjacent posts have the same color. Track two states: painting the current post the same color as the previous (but not the one before that), and painting it a different color.
Let same be the number of ways to paint the current post the same color as the previous, and diff be the number of ways to paint it a different color. Initialize for the first two posts, then iterate for the rest, updating the states.
classSolution {
public:int numWays(int n, int k) {
if (n ==0) return0;
if (n ==1) return k;
int same =0, diff = k;
for (int i =2; i <= n; ++i) {
int new_same = diff;
int new_diff = (same + diff) * (k -1);
same = new_same;
diff = new_diff;
}
return same + diff;
}
};
publicintnumWays(int n, int k) {
if (n == 0) return 0;
if (n == 1) return k;
int same = 0, diff = k;
for (int i = 2; i <= n; i++) {
int newSame = diff;
int newDiff = (same + diff) * (k - 1);
same = newSame;
diff = newDiff;
}
return same + diff;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
funnumWays(n: Int, k: Int): Int {
if (n ==0) return0if (n ==1) return k
var same = 0var diff = k
for (i in2..n) {
val newSame = diff
val newDiff = (same + diff) * (k - 1)
same = newSame
diff = newDiff
}
return same + diff
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defnumWays(self, n: int, k: int) -> int:
if n ==0:
return0if n ==1:
return k
same, diff =0, k
for _ in range(2, n+1):
new_same = diff
new_diff = (same + diff) * (k -1)
same, diff = new_same, new_diff
return same + diff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnnum_ways(n: i32, k: i32) -> i32 {
if n ==0 { return0; }
if n ==1 { return k; }
letmut same =0;
letmut diff = k;
for _ in2..=n {
let new_same = diff;
let new_diff = (same + diff) * (k -1);
same = new_same;
diff = new_diff;
}
same + diff
}
}
1
2
3
4
5
6
7
8
9
10
11
12
functionnumWays(n: number, k: number):number {
if (n===0) return0;
if (n===1) returnk;
letsame=0, diff=k;
for (leti=2; i<=n; i++) {
constnewSame=diff;
constnewDiff= (same+diff) * (k-1);
same=newSame;
diff=newDiff;
}
returnsame+diff;
}