題目描述
一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。
思路
每次可以跳一級或者兩級,那麼當有1級臺階的話,有1中跳法,2級臺階就有2種,3級臺階的話就要3種,4級臺階有5種。所以能看出來這是一個斐波那契數列。或者這樣想,一個n級的臺階,如果第一次跳1級,那麼剩下了(n-1)級臺階,跳法是f(n-1),如果第一次跳2級臺階,那麼剩下(n-2)級,跳法是f(n-2),所以n級臺階有f(n-1)+f(n-2)種跳法,其中,f(1) = 1,f(2) = 2。解決方案可以有2種,遞歸和非遞歸。
遞歸方式代碼參考
package com.sunshuo.java.offer;
/**
* <p>Title:Solution8a</p>
* <p>Description:跳臺階【遞歸方式】</p>
* @author SunShuo
* @version 1.0
* @date 2019年2月19日 上午9:38:20
*/
public class Solution8a {
public int JumpFloor(int target) {
if (target <= 2) {
return target;
}
return JumpFloor(target - 1) + JumpFloor(target - 2);
}
}
非遞歸方式代碼參考
package com.sunshuo.java.offer;
/**
* <p>Title:Solution8b</p>
* <p>Description:跳臺階【迭代方式】</p>
* @author SunShuo
* @version 1.0
* @date 2019年2月19日 上午9:43:41
*/
public class Solution8b {
public int JumpFloor(int target) {
if (target <= 2) {
return target;
}
int index1 = 1;
int index2 = 2;
int result = 0;
for (int i = 3; i <= target; i++) {
result = index1 + index2;
index1 = index2;
index2 = result;
}
return result;
}
}