爬楼梯问题——迭代or递归
采用递归法爬楼梯效率真是惊人啊,所以呢。用迭代吧。
下面是递归的。
#include <iostream> #include <vector> #include <math.h> #include <time.h> using namespace std; class Solution { public: int climbStairs(int n) { int step = 0; if(n == 1) { return 1; } else if (n == 2) { return 2; } else { step = climbStairs(n - 1) + climbStairs(n - 2); } return step; } }; int main(int argc, const char * argv[]) { Solution A; clock_t start,end; double time; start = clock(); int num; while (cin>>num) { cout<<A.climbStairs(num)<<endl; break; } end = clock(); time = (double)(end - start) / CLOCKS_PER_SEC; cout<<time<<endl; // insert code here... return 0; }
下面是迭代的。
#include <iostream> #include <vector> #include <math.h> #include <time.h> using namespace std; class Solution { public: int climbStairs(int n) { int step = 0; int k; if (n == 1) { step = 1; } else if (n == 2) { step = 2; } else { k = 2; ans[0] = 1; ans[1] = 2; while (k != n) { ans[k] = ans[k - 1] + ans[k - 2]; k++; } step = ans[k - 1]; } return step; } private: int ans[100]; }; int main(int argc, const char * argv[]) { Solution A; clock_t start,end; double time; start = clock(); int num; while (cin>>num) { cout<<A.climbStairs(num)<<endl; } end = clock(); time = (double)(end - start) / CLOCKS_PER_SEC; cout<<time<<endl; // insert code here... return 0; }
自己测试一下,如果数据量稍大,两种方法将会爆炸。。