問題
一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。
方法一:遞歸
public class Solution1 {
public int JumpFloor(int target) {
if (target == 1)
return 1;
else if (target ==2)
return 2;
else if (target>2){
return JumpFloor(target-1)+JumpFloor(target-2);
}
return 0;
}
}
方法二:while遍歷
public class Solution2 {
public int JumpFloor(int target) {
if (target == 1)
return 1;
else if (target ==2)
return 2;
else if (target>2){
int max1 = 1;
int max2 = 2;
int count =2;
while (count<target){
int temp = max2;
max2 = max2+max1;
max1 = temp;
count++;
}
return max2;
}
return 0;
}
}