[leetcode] Paint Fence


Paint Fence

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.

Dynamic programming.

dp0[i] stores total number of ways that i-1 is the same color with i;

dp1[i] stores total number of ways that i-1 is not the same color with i;

 

class Solution {
public:
    int numWays(int n, int k) {
        int dp0[n]; //num n, n-1 is the same
        int dp1[n]; //num n, n-1 is not the same
        if(k == 0) return 0;
        dp0[0] = 0;
        dp1[0] = k;
        for(int i = 1; i < n; i++){
            dp0[i] = dp1[i - 1];
            dp1[i] = (dp0[i - 1] + dp1[i - 1] )* (k - 1);
        }
        return dp0[n - 1] + dp1[n - 1];
    }
};

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.