leetcode276- Paint Fence- easy

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.

 

DP。

状态定义:same[i] 表示涂到第i根杆子的时候如果限制i和i-1颜色相同,总共有多少种刷的方法。 diffp[i] 表示涂到第i根杆子的时候如果限制i和i-1颜色不同,总共有多少种刷的方法。

状态转移方程:same[i] = 1 * diff[i - 1];    diff[i] = (k - 1) * (diff[i - 1] + same[i - 1]);  都是当前自己可选的颜色种类 * i - 1与i - 2之间需不需要相同的取舍。

返回结果:same[n - 1] + diff[n - 1]

 

实现:

class Solution {
    //same(n) = 1 * diff(n - 1)   diff(n) = (k - 1) * (diff(n - 1) + same(n - 1))
    public int numWays(int n, int k) {
        if (n <= 0 || k <= 0) {
            return 0;
        }
        
        int[] same = new int[n];
        int[] diff = new int[n];
        
        same[0] = 0;
        diff[0] = k;
        for (int i = 1; i < n; i++) {
            same[i] = 1 * diff[i - 1];
            diff[i] = (k - 1) * (diff[i - 1] + same[i - 1]);
        }
        return same[n - 1] + diff[n - 1];
        
    }
}

 

posted @ 2017-12-04 13:29  jasminemzy  阅读(174)  评论(0编辑  收藏  举报