题解 | #跳台阶扩展问题#
跳台阶扩展问题
http://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387
···
/**
@author jingbu
跳台阶扩展问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶(n为正整数)总共有多少种跳法。
可以跳上1级台阶,也可以跳上2级 --- 对于某一台阶,它可以从它的前一台阶和前二台阶跳上
可以跳上n级台阶 --- 可从前面的任一台阶跳上,就是把前面所有的跳法加起来+1(从刚开始直接跳上来)
/
public class Main {
public static void main(String[] args) {int target=5; Solution solution = new Solution(); System.out.println(solution.jumpFloorII(target));
}
}
class Solution {
public int jumpFloorII(int target) {
if(target==0){
return 0;
}
else if(target==1){
return 1;
}
else if(target==2){
return 2;
}
else { int sum=0; int[] arr=new int[target+1]; arr[0]=0; arr[1]=1; arr[2]=2; for (int i = 3; i < target + 1; i++) { for (int j = 0; j < i; j++) { sum+=arr[j]; } arr[i]=sum+1; sum=0; } return arr[target]; } }
}
···