Paint Fence

There are n posts and 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. n and k are non-zero integers.

Example

(3, 2) => 6

P1 P2 P2
1  1  2
1  2  1
2  1  1
2  2  1
2  1  2
1  2  2

Analysis

We only want the number of ways not the actual solutions. So we can try DP.

Single Sequence DP

Code

There is only one layer of dependencies so we can compress the active states.

Code w/ State Compression

Time Complexity

#subproblems * time/subproblem = 2n * O(1) = O(n)

Last updated