LeetCode(Google) 0276 Paint Fense

LeetCode 276 Paint Fense

There is a fence with n posts, each post can be painted with one of the k colors.java

You have to paint all the posts such that no more than two adjacent fence posts have the same color.post

Return the total number of ways you can paint the fence.code

Note:
n and k are non-negative integers.it

class Solution {
    public int numWays(int n, int k) {
        if (n == 0 || k == 0) return 0;
        if (n == 1) return k;
        // same[i] : 第i个post和第i-1个post颜色相同
        int[] same = new int[n];
        // diff[i] : 第i个post和第i-1个post颜色不一样
        int[] diff = new int[n];
        same[0] = same[1] = k;
        diff[0] = k;
        diff[1] = k * (k - 1);
        for (int i = 2; i < n; ++i) {
            same[i] = diff[i-1];
            diff[i] = (k - 1) * same[i-1] + (k - 1) * diff[i-1];
        }
        return same[n-1] + diff[n-1];
    }
}
相关文章
相关标签/搜索