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?
Subscribe to see which companies asked this question
解法一:
思路:n级台阶可以看成n-1级台阶直接一步跨上去,或者n-2步台阶,跨两步上去,由于n-1和n-2的起点不同,终点相同,所以n-1的方式和n-2的方式一定没有重复的,所以S(n)=S(n-1)+S(n-2)
class Solution {
public:
int climbStairs(int n) {
if(n<=2)
return n;
else{
vector<int> ways;
ways.push_back(1);
ways.push_back(2);
for(int i = 2; i< n; i++){
int way = ways[i-1]+ways[i-2];
ways.push_back(way);
}
return ways[n-1];
}
}
};
其他解法暂时先留着。
网友评论