Leetcode
Dynamic Programming
276 Paint Fence

276. Paint Fence

1. Question

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.

2. Implementation

(1) DP
1
class Solution {
2
public int numWays(int n, int k) {
3
if (n == 0 || k == 0) {
4
return 0;
5
}
6
7
int[] ways = new int[n + 1];
8
if (n == 1) {
9
return k;
10
}
11
12
if (n == 2) {
13
return k * k;
14
}
15
16
ways[1] = k;
17
ways[2] = k * k;
18
19
for (int i = 3; i <= n; i++) {
20
ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]);
21
}
22
return ways[n];
23
}
24
}
Copied!

3. Time & Space Complexity

DP: 时间复杂度O(n), 空间复杂度O(n)