LintCode_514 Paint Fence

题目

here 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.

 注意事项

n and k are non-negative integers.

样例

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

思路
动态规划问题
当我前i个posts有多少种可能性是 如果第i-1个颜色和第i个颜色不同时 s[i] = (k-1)*s[i-1];
如果第i-1个颜色和第i个颜色相同时因为不能有超过2个颜色相同,则和第i-2个颜色一定不同 s[i] = s[i-2]*(k-1);
s[i] = s[i-1]*(k-1) + s[i-2]*(k-1)
C++代码
int numWays(int n, int k) {
        // Write your code here
        if(n == 0) return 0;
        if(n == 1) return k;
        if(n == 2) return k*k;
        int i;
        int a[n];
        a[0] = k;
        a[1] = k*k;
        for(i = 2; i < n; ++i)
        {
            a[i] = a[i-1]*(k-1) + a[i-2]*(k-1);
        }
        return a[i-1];
}
View Code

 

posted @ 2016-05-10 11:51  红岸的电波  阅读(221)  评论(0编辑  收藏  举报