https://oj.leetcode.com/problems/climbing-stairs/
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?
public int climbStairs(int n)
这一题和unique path并为斐波那契之后dp的两块敲门砖之一。所以leetcode给的难度也是easy。
本质上是一个一维dp。f(0) = 1, f(1) = 1, 剩下的f(i) = f(i - 1) + f(i - 2) 这么设定的理由其实很简单,就是我在第i格的时候,我可以从i - 1那里走一格,或者从i - 2那里走两格。也就是我走到i的时候,我的解集数目就是i - 1那里的解集数目加上i - 2那里的解集数目。
正如我之前所说的,只要是单方向从前往后或者从后往前继承子集的dp,都可以在空间上缩小一个级别。所以这一题虽然是一维dp,但是实际空间是常数级别的就可以了。请看代码:
public int climbStairs(int n) {
if(n <= 2)
return n;
int prev = 1;
int next = 2;
for(int i = 3; i <= n; i++){
next = prev + next;// f(j) = f(j - 1) + f(j - 2)
prev = next - prev;// f(j - 1) = f(j) - f(j - 2)
}
return next;
}
289

被折叠的 条评论
为什么被折叠?



