0276. Paint Fence
Last updated
Last updated
**Input:** n = 3, k = 2
**Output:** 6
**Explanation:** 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.**Input:** n = 1, k = 1
**Output:** 1**Input:** n = 7, k = 2
**Output:** 42class Solution {
public int numWays(int n, int k) {
// edge cases
if (n <= 0 || k <= 0) return 0;
if (n == 1) return k;
// dp
int same = k;
int diff = k * (k - 1);
for (int i = 2; i < n; i++) {
int tmp = diff;
diff = (same + diff) * (k - 1);
same = tmp;
}
return diff + same;
}
}