方法一
public class Solution {
/**
* @param n non-negative integer, n posts
* @param k non-negative integer, k colors
* @return an integer, the total number of ways
*/
public int numWays(int n, int k) {
if(n==1){
return k;
}
if(n==2){
return k*k;
}
int[] arr=new int[n];
arr[0]=k;arr[1]=k*k;
for(int i=2;i<n;i++){
arr[i]=(arr[i-1]+arr[i-2])*(k-1);
}
return arr[n-1];
}
}
注意:arr[0]=k;arr[1]=k*k;切不可以忘记!
方法二
public class Solution {
/**
* @param n non-negative integer, n posts
* @param k non-negative integer, k colors
* @return an integer, the total number of ways
*/
public int numWays(int n, int k) {
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;
}
}
比较两种方法的运行时间是相同的,但是方法二不需要去建立数组!!!!!!!
lintcode514栅栏染色(动态规划easy)
最新推荐文章于 2022-05-10 12:05:05 发布