美文网首页
9. 跳台阶

9. 跳台阶

作者: 丶沧月 | 来源:发表于2019-03-13 22:30 被阅读0次

    题目描述

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

    问题分析

    设f(n)表示青蛙跳上n级台阶的跳法数。当只有一个台阶时,
    即n = 1时, 只有1中跳法;
    当n = 2时,有两种跳法;
    当n = 3 时,有3种跳法;
    当n很大时,青蛙在最后一步跳到第n级台阶时,有两种情况:
    一种是青蛙在第n-1个台阶跳一个台阶,那么青蛙完成前面n-1个台阶,就有f(n-1)种跳法,这是一个子问题。
    另一种是青蛙在第n-2个台阶跳两个台阶到第n个台阶,那么青蛙完成前面n-2个台阶,就有f(n-2)种情况,这又是另外一个子问题。

    两个子问题构成了最终问题的解,所以当n>=3时,青蛙就有f(n)=f(n-1)+f(n-2)种跳法。

    递归实现:O(n2) O(n)

    public class Solution {
        public int JumpFloor(int target) {
            if(target == 1 || target ==2) {
                return target;
            }else{
                return JumpFloor(target - 1) + JumpFloor(target - 2);
            }
        }
    }
    

    迭代实现 O(n) O(n)

    问题分析

    可以使用一个数来保存之前计算的结果,防止重复计算

    
    public class Solution {
        public int JumpFloor(int target) {
        
            if (target <= 0) {
                return 0;
            }
            if (target == 1) {
                return 1;
            }
            if (target == 2) {
                return 2;
            }
           
            int first = 1;
            int second = 2;
            int third = 0;
            
            for(int i = 3; i <= target; i++) {
                third = first + second;
                first = second;
                second = third;
            }
            return third;
        }
    

    相关文章

      网友评论

          本文标题:9. 跳台阶

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