• 【算法编程】青蛙跳台阶


    题目来源:牛客网剑指offer

    题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

    解题思路:f(n) = f(n-1) + f(n-2)

    C++: 3ms 492k

    #include <iostream>
    using namespace std;
    
    class Solution {
    public:
        int jumpFloor(int number) {
            int jump0 = 1;
            int jump1 = 1;
            while(number-->1){
                jump1 += jump0;
                jump0 = jump1 - jump0;
            }
            return jump1;
        }
    };
    
    int main()
    {
        Solution obj;
        int n;
        while(cin>>n){
            cout<<obj.jumpFloor(n)<<endl;
        }
        cin.get();
        cin.get();
    }

    Python: 30ms 5732k

    # -*- coding:utf-8 -*-
    import sys
    class Solution:
        def jumpFloor(self, number):
            # f(n) = f(n-1) + f(n-2)
            jump0 = 1 # two steps: 1,1;2 jump0+jump1
            jump1 = 1 # one step: 1
            while (number>1):
                jump1 += jump0
                jump0 = jump1 - jump0
                number -= 1
            return jump1
    
    
    if __name__ == '__main__':
        obj = Solution()
        while (1):
            x = input()
            print obj.jumpFloor(x)
  • 相关阅读:
    时间安排还是很不合理
    ZOJ Problem Set
    ZOJ Problem Set
    ZOJ Problem Set
    ZOJ Problem Set
    还是很水啊!!!
    pragma mark
    IOS应用发布NSLog的如何注释
    设定时间让应用从后台回来是否重新启动应用
    Mac 上SVN上传.a文件
  • 原文地址:https://www.cnblogs.com/xiangfeidemengzhu/p/9170239.html
Copyright © 2020-2023  润新知