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.

Tips:

注意题目的意思是不能超过两个相邻的颜色一致。 这种方案总数问题很多都是用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)

改进:空间复杂度O(1)

Code:

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

改进:

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

results matching ""

    No results matching ""