Paint Fence(276)

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.post

Return the total number of ways you can paint the fence.优化

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

思路: 注意题目的意思是不能超过两个相邻的颜色一致。 这种方案总数问题不少都是用dp。 由于超过相邻两个颜色一致,即不能三个颜色一致,那么x的涂色不能和前一个一致|| 不能和前前个涂色一致。
即f[x] = f[x - 1] K - 1 + f[x - 2] k - 1; 除了递推,还要考虑base 状况。 若是n 或者k 任意一个为0, 那么f[x] = 0。 若是n == 1, 那么就是k。 it

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

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];
    }
}

空间改进:class

对于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];
    }
}