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[0]表示第一根栅栏以及之前栅栏总共可以涂色的方法数量;(栅栏数量为i时的方法数量)
num[1]表示第二根栅栏以及之前栅栏总共可以涂色的方法数量;(栅栏数量为i+1时的方法数量)
num[ 2]表示第三根以及之前总共可以涂色的方法数量
num[3] = (k-1)*num[0] + (k-1)*num[1];
以此类推到n为止。
代码如下:
<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>