276 Paint Fence

1. Question

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.

2. Implementation

(1) DP

class Solution {
    public int numWays(int n, int k) {
        if (n == 0 || k == 0) {
            return 0;
        }

        int[] ways = new int[n + 1];
        if (n == 1) {
            return k;
        }

        if (n == 2) {
            return k * k;
        }

        ways[1] = k;
        ways[2] = k * k;

        for (int i = 3; i <= n; i++) {
            ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]);
        }
        return ways[n];
    }
}

3. Time & Space Complexity

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

Last updated