Paint Fence

Posted amazingzoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 Notice

n and k are non-negative integers.

Example

Given n=3, k=2 return 6

      post 1,   post 2, post 3
way1    0         0       1 
way2    0         1       0
way3    0         1       1
way4    1         0       0
way5    1         0       1
way6    1         1       0
 1 class Solution {
 2 public:
 3     /**
 4      * @param n non-negative integer, n posts
 5      * @param k non-negative integer, k colors
 6      * @return an integer, the total number of ways
 7      */
 8     int numWays(int n, int k) {
 9         // Write your code here
10         
11         // dp[i] indicates the number of ways of painting until i
12         // If the color at i is different from its former fence, then there are (k - 1) choices times dp[i - 1]; If the color at i is the same from its former fence, then it must be different from (i - 2)th fence, so there are (k - 1)  * dp[i - 2] choices.
13         vector<int> dp = {0, k, k * k};
14         int index = 3;
15         while (index <= n) 
16             dp.push_back((k - 1) * (dp[index - 1] + dp[index++ - 2]));
17         return dp[n];
18     }
19 };

 

以上是关于Paint Fence的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 276: Paint Fence

Paint Fence

276. Paint Fence

Paint Fence

276. Paint Fence

514. Paint Fence