一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。
思路:假設有n個臺階,res種跳法,n=1 res = 1; n=2,res=2; n=3.res =3; n=4,res =5; 排列組合一個一個試過了。明顯是個斐波那契數列,這裏i從3開始。
public class Solution {
public int JumpFloor(int target) {
if (target == 1 || target == 2)
return target;
int res = 0;
int a = 1;
int b = 2;
for(int i = 3; i <= target; i++){
res = a + b;
a = b;
b = res;
}
return res;
}
}