問題描述:
我們有一個柵欄,它有n
個柱子,現在要給柱子染色,有k
種顏色可以染。
必須保證不存在超過2個相鄰的柱子顏色相同,求有多少種染色方案。
注意事項
n
和k
都是非負整數
n
= 3, k
=
2, return 6
post 1, post 2, post 3
way1 0 0 1
way2 0 1 0
way3 0 1 1
way4 1 0 0
way5 1 0 1
way6 1 1 0
狀態轉移方程爲 a[i]=(a[i-1]+a[i-2])*(k-1)
代碼:
class Solution {
public:
/*
* @param n: non-negative integer, n posts
* @param k: non-negative integer, k colors
* @return: an integer, the total number of ways
*/
int numWays(int n, int k) {
// write your code here
if(n==1) return k;
if(n==2) return k*k;
else
{
int a[n];
for(int i=0;i<n;i++)
{
a[i]=k;
a[1]=k*k;
if(i>1)
a[i]=(a[i-1]+a[i-2])*(k-1);
}
return a[n-1];
}
}
};
感想:
這個題沒有考慮出狀態轉移方程