问题描述:
我们有一个栅栏,它有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];
}
}
};
感想:
这个题没有考虑出状态转移方程