面試XXX金服面試幾個算法題中的一個
有n個臺階,每次走1或2個臺階,一共有幾種走法?
用了2個小時,寫了排列組合的實現算法。吃過飯發現原來是 斐波那契數列 。。。。。。可是。。。可但是。。。
/**
* 有n個臺階,每次走1或2個臺階,一共有幾種走法?
*/
private static long calc(int count) {
//計算出每步2個臺階, 最大走的次數step2
int maxStep2 = count / 2;
long waySum = 0;
int countStep1 = 0;
//遍歷0 - step2
for(int countStep2 = 0; countStep2 <= maxStep2; countStep2 ++){
//計算出每步1個臺階的次數
countStep1 = count - 2*countStep2;
//走countStep1 + countStep2 次中,有countStep1次,進行排列組合
//計算公式:;C(n,m)=C(n,n-m)。(n≥m)
long perWay = factorial(countStep1 + countStep2)
/ factorial(countStep1)
/ factorial(countStep2);
waySum += perWay;
}
return waySum;
}
/**
* 階乘
* @param num
* @return
*/
public static long factorial(int num){
long sum=1;
if(num < 0){//判斷傳入數是否爲負數
throw new IllegalArgumentException("必須爲正整數!");//拋出不合理參數異常
}
for(int i=1;i<=num;i++){//循環num
sum *= i;//每循環一次進行乘法運算
}
return sum;//返回階乘的值
}