http://oj.leetcode.com/problems/climbing-stairs/
走台阶的题目,转换出数学模型之后,就是Fibonacci数列。后一个数等于前两个数的和。
递归版本超时,代码如下:
class Solution { public: int walk(int sum) { if(sum == 0 ) return 1; if(sum ==1) return 1; return walk(sum-1)+walk(sum-2); } int climbStairs(int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return walk(n); } };
然后改成顺序的了,AC,代码如下:
#include <iostream> using namespace std; class Solution { public: int climbStairs(int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int* arr = (int*)malloc(sizeof(int)*(n+2)); arr[0] = 1; arr[1] = 1; for(int i = 2;i<=n;i++) arr[i] = arr[i-1]+arr[i-2]; return arr[n]; } }; int main() { Solution myS; int ans = myS.climbStairs(25); cout<<ans<<endl; return 0; }
加油!