題目來源:牛客網劍指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)