题目来源:牛客网剑指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)