这是经典的dp问题,比较简单,听说递归不能过,所以写的循环。而且没有用数组,因为不知道n的范围,就直接两个变量不变更新。
class Solution {
public:
int climbStairs(int n) {
int ans = 0 , a = 1 , b = 2;
if( n == 1 ) return 1;
else if( n == 2 ) return 2;
else{
for( int i = 3 ; i <= n ; i++ ){
ans = a + b;
a = b;
b = ans;
}
}
return ans;
}
};