1

Paint Fence

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。 因为超过相邻两个颜色一致,即不能三个颜色一致,那么x的涂色不能和前一个一致|| 不能和前前个涂色一致。
即f[x] = f[x - 1] K - 1 + f[x - 2] k - 1; 除了递推,还要考虑base 情况。 如果n 或者k 任意一个为0, 那么f[x] = 0。 如果n == 1, 那么就是k。

时间复杂度: O(n)
空间复杂度: O(n)

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

空间改进:

对于dp来说,为了存储状态开辟的数组可以变成动态数组来优化空间。 因为当前状态仅仅只和上一个,还有上上个有关。所以实际只需要开辟3个空间。这样空间复杂度降为O(1).

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

colorfuladventure
4 声望4 粉丝

引用和评论

0 条评论