美文网首页
剑指offer-跳台阶

剑指offer-跳台阶

作者: 纳萨利克 | 来源:发表于2019-09-28 14:30 被阅读0次

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

思路
跳2步到n级台阶,还剩n-2级,从起始点跳到n-2级台阶的跳法有xx1种
跳1步到n级台阶,还剩n-1级,从起始点跳到n-1级台阶的跳法有xx2种
跳到n级台阶,只需要跳到n-2级台阶的种数+跳到n-1级台阶的种数
fibonacci

Java

public class Solution {
    public int JumpFloor(int target) {
      if (target<=2) {
        return target;
      }
      int sum = 2;
      int one = 1;
      for (int i = 3; i <= target; i++) {
        sum = one + sum;
        one = sum - one;
      }
      return sum;
    }
}

相关文章

网友评论

      本文标题:剑指offer-跳台阶

      本文链接:https://www.haomeiwen.com/subject/xgwzuctx.html