# [leetcode 276] Paint Fence

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.

num[1]表示第二根栅栏以及之前栅栏总共可以涂色的方法数量；（栅栏数量为i+1时的方法数量）

num[ 2]表示第三根以及之前总共可以涂色的方法数量

num[3] = (k-1)*num[0] + (k-1)*num[1];

<span style="font-size:14px;">class Solution {
public：
int numWays(int n, int k) {
// 当n=0时返回0
if(n == 0 || K == 0)
return 0;
int num[] = {k , k*k, 0};
if(n <= 2){
return num[n];
}
for(int i = 2; i < n; i++){
// 递推式：第三根柱子要么根第一个柱子不是一个颜色，要么跟第二根柱子不是一个颜色
num[3] = (k - 1) * (num[1] + num[2]);
num[1] = num[2];
num[2] = num[3];
}
return dp[3];
}
}</span>

#### [leetcode] 276. Paint Fence 解题报告

2016-03-12 05:44:37

#### LeetCode 276. Paint Fence（篱笆涂色）

2016-04-14 00:48:41

#### [LeetCode276]Paint Fence

2015-11-26 05:33:49

#### lintcode paint-fence 栅栏染色

2016-07-26 16:31:32

#### Leetcode 276 Paint Fence

2017-03-28 10:10:54

#### [leetcode] 256. Paint House 解题报告

2016-03-13 03:03:02

#### 【编程】【leetcode】276 Paint Fence

2017-04-09 18:40:02

#### leetcode 587. Erect the Fence 最短围栏 + 凸包优化

2017-12-21 09:05:23

#### Paint Fence 栅栏涂色

2016-03-19 21:44:51

#### [leetcode] 265. Paint House II 解题报告

2016-03-05 12:50:21