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

• 本文已收录于以下专栏：

## [LeetCode276]Paint Fence

There is a fence with n posts, each post can be painted with one of the k colors.You have to paint a...

## Leetcode——276.Paint Fence

DescriptionThere is a fence with n posts, each post can be painted with one of the k colors.You have...

## [Leetcode]Paint House

There are a row of n houses, each house can be painted with one of the three colors: red, blue or gr...

## Leetcode 256. Paint House (Medium) (cpp)

Leetcode 256. Paint House (Medium) (cpp)

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

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)