【算法编程】青蛙跳台阶

题目来源:牛客网剑指offerios

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

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

C++: 3ms 492kblog

#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 5732kutf-8

# -*- 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)
相关文章
相关标签/搜索