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?
爬楼梯问题,其实是一个斐波那契数列问题,fn = fn-1+ fn-2; 使用dp的思想求解,时间复杂度O(n), 空间复杂度O(1)
class Solution {
public:
int climbStairs(int n) {
//sanity check
if (n <= 1) return 1;
// if (n == 2) return 2;
int pre = 1;
int prep =1;
int cur = 0;
for (int i = 2; i <= n; i++) {
cur = pre + prep;
prep = pre;
pre = cur;
}
return cur;
}
};
No comments:
Post a Comment