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.
n and k are non-negative integers.
Solution:
Using DP. To know how many ways to paint current house, we need to know two things. First, the total number of ways to paint previous houses. Second, We need to know whether the house in the last round is paint the color as same as the house before it.
So, we can create a Nx2 array to same the total number of ways to paint current n houses for first the current house is paint differently with previous one and second the current house is paint the same color as previous one.
To further optimize the code, could just use two variable to save results.
Round 2 solution:
For the first post, there is total k ways to paint it. For the second post, if it is paint differently than first one, there is (k-1)*k ways, it is paint in a same way, there is k. Starting from the 3rd post, if paint differently, we add up the case where first if previous one was paint differently, second if previous one is paint same.
No comments:
Post a Comment