> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/dynamic-programming/276-paint-fence.md).

# 276     Paint Fence

## 276. [Paint Fence](https://leetcode.com/problems/paint-fence/description/)

## 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**

```java
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)
