Wednesday, September 30, 2020

L 276. Paint Fence ------E

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.

Example:

Input: n = 3, k = 2
Output: 6
Explanation: Take c1 as color 1, c2 as color 2. All possible ways are:

            post1  post2  post3      
 -----      -----  -----  -----       
   1         c1     c1     c2 
   2         c1     c2     c1 
   3         c1     c2     c2 
   4         c2     c1     c1  
   5         c2     c1     c2 

  6 c2 c2 c1 

A:

DP  

             想出来     递推公式   

If n > 2, then the result can be derived by appending 2 posts with the same color that is different from the last one to the result of n-2 and appending 1 post with a color that's different from the last one to the result of n-1.


class Solution {
public:
    int numWays(int n, int k) {
        if(n == 0 || k == 0)
            return 0;
        vector<int> sameAsLast(n,0);
        vector<int> diffAsLast(n,0);
        diffAsLast[0] = k;
        for(int i = 1;i<n;i++){
            sameAsLast[i] = diffAsLast[i-1];
            diffAsLast[i] = (k-1)*( sameAsLast[i-1] + diffAsLast[i-1]);
        }
        return sameAsLast[n-1] + diffAsLast[n-1];
    }
};




No comments:

Post a Comment