LeetCode(Google) 0276 Paint Fense

proheart

LeetCode 276 Paint Fense

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.

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];
    }
}
阅读 1.4k

来刷算法
Learn data structure and algorithm using java.

Developer, Java & Android

38 声望
20 粉丝
0 条评论

Developer, Java & Android

38 声望
20 粉丝
文章目录
宣传栏