Climbing Stairs
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?
/** 整理的提交代码
* 处理复杂度为O(n)
* 主要思路:最简单的方法是使用递归(f(n)=f(n-1)+f(n-2)),但是n较大时效率太低,时间复杂度以O(2n)指数递增。
* 使用递归的主要问题是:1、函数调用的开销,2、可能的重复计算额外开销,3、可能的调用栈溢出错误。
* 为了避免重复计算,可以将前面计算的结果保存,如果后面需要则查找之前保存结果。
* 简单方法是通过从小往大算,其实就是用循环的方法实现递归,但循环变量从小往大增加。
* 提交结果:
* (Judge Small)
* Run Status: Accepted!
* Program Runtime: 4 milli secs (基本在几毫秒)
* Progress: 10/10 test cases passed.
* (Judge Large)
* Run Status: Accepted!
* Program Runtime: 8 milli secs (基本稳定在几毫秒左右)
* Progress: 45/45 test cases passed.
*/
#include <cassert>
#include <iostream>
using namespace std;
class Solution {
public:
// 如果n太大可能会结果会溢出,可以使用long long。
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 1)
{
return 1;
}
if (n == 2)
{
return 2;
}
int NMinusOne = 2; // f(n-1)
int NMinusTwo = 1; // f(n-2)
int N;
for (int i = 3; i <=n; i++)
{
N = NMinusOne + NMinusTwo; // f(n) = f(n-1) + f(n-2)
// 更新f(n-1)和f(n-2)
NMinusTwo = NMinusOne;
NMinusOne = N;
}
return N;
}
};
int main()
{
int n = 0;
cout << "input stair steps: ";
cin >> n;
assert(n != 0);
Solution s;
int result = s.climbStairs(n);
cout << "result: " << result << endl;
return 0;
}