zoukankan      html  css  js  c++  java
  • 跳台阶

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

    分情况讨论:当n=1 ,n=2 ,n>=2

    当n>=2时又从第一次开始讨论,第一次可以跳两步或者一步,剩下的就是f(n-1)或者f(n-2)步,这是两种不同的方案进行相加,就可以看出规律为斐波拉契数列。但是要注意的是初值为1而不是0,以及台阶和index的关系。

     resolution1:自底向上

     public int JumpFloor(int target) {
              int counts = 0;
            int[] countArray = new int[target];
            countArray[0] = 1;
            if(target>2 || target ==2){
                countArray[1] = 2;
                for(int i = 2;i < target; i++){
                    countArray[i] = countArray[i-1] + countArray[i-2];
                }
                counts = countArray[target - 1];
            }else if(target == 1){
                counts = 1;
            }
            return counts;
    
        }

    resolution:自顶向下

    需要注意的是最后判断target>2时不能用while,否则就是一个死循环,应该直接用if,执行了判断语句之后就直接跳出循环,而while会一直判断,满足条件又会继续循环。

    while与if语句的最大的相同点是都有至少一步的判断。
    最大的不同点是:IF语句运行完毕后,接着运行下面的语句。而While中的执行语句运行完毕后,还要进行继续判断条件是否符合循环条件,根据判断的条件,返回执行语句或继续运行下面的程序。
     public int JumpFloor(int target) {
             int result = 0;
            if(target == 1)  result = 1;
            if(target == 2)  result =2 ;
            if(target >2 ){
                result = JumpFloor(target -1) + JumpFloor(target - 2);
            }
            return result;
        }
    欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
  • 相关阅读:
    Mayan游戏 (codevs 1136)题解
    虫食算 (codevs 1064)题解
    靶形数独 (codevs 1174)题解
    黑白棋游戏 (codevs 2743)题解
    神经网络 (codevs 1088) 题解
    The Rotation Game (POJ 2286) 题解
    倒水问题 (codevs 1226) 题解
    银河英雄传说 (codevs 1540) 题解
    生日蛋糕 (codevs 1710) 题解
    第一章 1.11 高阶函数
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326842.html
Copyright © 2011-2022 走看看