leetcode276- Paint Fence- easy

Posted jasminemzy

tags:

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

 


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

[LeetCode] 276. Paint Fence 粉刷篱笆

[LeetCode] 276. Paint Fence_Easy tag: Dynamic Programming

276. Paint Fence

276. Paint Fence

276. Paint Fence

LeetCode Paint Fence