牛客题霸NC68跳台阶Java题解
https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=117&&tqId=34990&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
方法1:动态规划
解题思路:此题与斐波那契数列相似。
当target<=1时,返回1,当target==2时,返回2,当target>=3时,返回前两项和。
public class Solution { public int JumpFloor(int target) { if(target <= 1){ return 1; } if(target == 2){ return 2; } int[] res = new int[target+1]; //用来存储每个target对应的跳法。 res[0] = 1; res[1] = 1; res[2] = 2; for(int i = 3;i<=target;i++){ res[i] = res[i-1]+res[i-2]; } return res[target]; } }
方法2:递归
解题思路:当target<=1时,返回1,当target>=2时,返回 return JumpFloor(target-1)+JumpFloor(target-2)。
public class Solution { public int JumpFloor(int target) { if(target <= 1){ return 1; } return JumpFloor(target-1)+JumpFloor(target-2); } }