一、跳臺階
1、題目描述
一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。
輸入:一個整數n
輸出:跳上n個臺階的跳法種數
2、思路分析
思路和斐波那契數列的類似。
3、實現代碼
/**
* @author 0416
* @date 2019/12/6
**/
public class JumpStep {
/**
* Method one
* @param target
* @return
*/
public static int JumpFloor(int target) {
if(target == 0){
return 0;
}
if(target == 1){
return 1;
}
if(target == 2){
return 2;
}
return JumpFloor(target - 1) + JumpFloor(target - 2);
}
/**
* Method two
* @param target
* @return
*/
public static int JumpStep(int target){
if(target == 0){
return 0;
}
int tempOne = 0;
int tempTwo = 1;
for (int i = 1; i <= target; i++) {
int temp = tempOne + tempTwo;
tempOne = tempTwo;
tempTwo = temp;
}
return tempTwo;
}
public static void main(String[] args) {
int result = JumpFloor(13);
System.out.println(result);
int result2 = JumpStep(13);
System.out.println(result2);
}
}
二、變態跳臺階
1、題目描述
一隻青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。
輸入:一個整數n
輸出:跳上n個臺階的跳法種數
2、思路分析
1、動態規劃。f(n) = f(n-1) + f(n-2) + … + f(0) ,而且每一級臺階都一定有 1 種跳法。
2、數學公式。
由 f(n) = f(n-1) + f(n-2) + … + f(0) 和 f(n-1) = f(n-2) + f(n-3) + … + f(0) 可得:
f(n-1) = f(n-2) + f(n-3) + … + f(0),即:f(n) = 2 ^ (n - 1)
3、實現代碼
/**
* @author 0416
* @date 2019/12/6
**/
public class AdvancedJumpStep {
/**
* Method one
* @param target
* @return
*/
public static int advancedJumpStep(int target){
if(target <= 0){
return 0;
}
int[] times = new int[target];
times[0] = 1;
for (int i = 1; i < target; i++) {
//每級臺階的跳法都初始化爲1
times[i] ++;
for (int j = 0; j < i; j++) {
times[i] += times[j];
}
}
return times[target - 1];
}
/**
* Method two
* @param target
* @return
*/
public static int advancedJumpFloor(int target){
if(target <= 0){
return 0;
}
return (int)Math.pow(2, target - 1);
}
public static void main(String[] args) {
System.out.println(advancedJumpStep(13));
System.out.println(advancedJumpFloor(13));
}
}