Climbing Stairs
Total Accepted: 83180 Total Submissions: 234611 Difficulty: Easy
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?
思路:
很容易想到用递归。但是递归重复计算,耗时,耗内存。
因此,就改用循环来计算。n节阶梯的方法数等(n-1)节阶梯的方法数(最后跨一步)+(n-2)节阶梯的方法数(最后跨两步)。
class Solution {
public:
int climbStairs(int n) {
if(n==1){
return 1;
}else if(n==2){
return 2;
}
int num1=1;
int num2=2;
int num3;
for(int i=3;i<=n;i++){
num3=num1+num2;
num1=num2;
num2=num3;
}
return num3;
}
};