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?
Solution 1
idea: recursive function, however, run out of limit time
class Solution {
public:
int climbStairs(int n) {
if (n==1)
return 1;
else if (n==2)
return 2;
else
return climbStairs(n-1)+climbStairs(n-2);
}
};
Solution 2
idea: similar to Fibonacci number
class Solution {
public:
int climbStairs(int n) {
if (n==1)
return 1;
else if (n==2)
return 2;
else{
int ppre = 1;
int pre = 2;
for (int i = 3; i < n; i++){
int tmp = pre;
pre = ppre+pre;
ppre = tmp;
}
return pre+ppre;
}
}
};