描述
我们有一个栅栏,它有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
这是一道数学题,从第三个栅栏开始,有两种选择,第一种是与前一个栅栏颜色不同。第二种是与前一个栅栏颜色相同,那就是与前一个的前一个颜色不同。
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;
}
int now=0,lastlast=k,last=k*k;
for(int i=2;i<n;i++){
now=(last+lastlast)*(k-1);
lastlast=last;
last=now;
}
return now;
}
};