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];
    }
}
相關文章
相關標籤/搜索