Leetcode climbing-stair

此题不难,首先先写出递归的方法:
上第n层台阶是有两种情况
1,一步上去
2,跨两步上去
即climbStair(n)=climbStair(n-1)+climbStair(n-1)
即可得到他的递归方法。
根据递归方法写出循环的方法即可

/**********************************************************************************
* * You are climbing a stair case. It takes n steps to reach to the top.
* * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
* * **********************************************************************************/

#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <vector>
using namespace std;
int climbStairs(int n) {
 if (n <= 3) return n;
 int a[2] = { 2,3 };
 for (int i = 4; i <= n; i++) {
 int t = a[0] + a[1];
 a[0] = a[1];
 a[1] = t;
 }
 return a[1];
}
//Time too long
int climbStairs2(int n) {
 if (n <= 3) return n;
 return climbStairs2(n - 1) + climbStairs2(n - 2);
}
//测试,两种方法所耗时间,
int main()
{
 clock_t start_time = clock();
 cout << climbStairs(40) << endl;
 clock_t end_time = clock();
 cout << "Running time :" << (end_time - start_time) << "ms" << endl;
 clock_t start_time1 = clock();
 cout << climbStairs2(40) << endl;
 clock_t end_time1= clock();
 cout << "Running time :" << (end_time1 - start_time1)<< "ms" << endl;
}

你可能感兴趣的:(LeetCode)