Question
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?
Code
#include<iostream>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
if (n <= 0) return 0;
if (n == 1 || n == 2 || n == 3) return n;
int prev = 3;
int prevprev = 2;
int res = 0;
for (int i = 3; i < n; ++i) {
res = prevprev + prev;
prevprev = prev;
prev = res;
}
return res;
}
};
int main() {
int n = 4;
Solution so;
cout << so.climbStairs(n) << endl;
system("pause");
return 0;
}