zoukankan      html  css  js  c++  java
  • 剑指Offer-8.跳台阶(C++/Java)

    题目:

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

    分析:

    实际上就是斐波那契数列的一个应用,青蛙跳上n级台阶的跳法数等于跳上n-1阶的跳法数加上n-2阶的跳法数,因为青蛙可以从n-1阶跳1级到达n阶,也可以从n-2阶跳2级到达n阶,也就是f(n) = f(n-1) + f(n-2)。

    程序:

    C++

    class Solution {
    public:
        int jumpFloor(int number) {
            if(number == 1) return 1;
            if(number == 2) return 2;
            int fNum = 1;
            int sNum = 2;
            int temp = 0;
            for(int i = 3; i <= number; ++i){
                temp = sNum;
                sNum = fNum + sNum;
                fNum = temp;
            }
            return sNum;
        }
    };

    Java

    public class Solution {
        public int JumpFloor(int target) {
            if(target == 1) return 1;
            if(target == 2) return 2;
            int fNum = 1;
            int sNum = 2;
            int temp = 0;
            for(int i = 3; i <= target; ++i){
                temp = sNum;
                sNum = fNum + sNum;
                fNum = temp;
            }
            return sNum;
        }
    }
  • 相关阅读:
    python爬取图片
    IDEA创建SpringBoot项目报错,不能连接https://start.spring.io/
    ES模块化的理解
    Web标准(网站标准)理解
    Mongodb安装
    Linux Ntp时间同步服务
    SentinelResource 注解
    Sentinel的流量控制
    Sentinel简介
    nacos安装
  • 原文地址:https://www.cnblogs.com/silentteller/p/11851749.html
Copyright © 2011-2022 走看看