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 class Solution {
public int climbStairs(int n) {
//f(n) = f(n-1) + f(n-2),f(1) = 1,f(0) = 1;
//表示当前位置所有不同走法数
if(n < 2) return n;
/*
int[] f = new int[n+1];
f[0] = 1;
f[1] = 1;
for(int i = 2;i<n+1;i++) {
f[i] = f[i-1] + f[i-2];
}
*/
int a=1,b=1;
for(int i = 2;i<n+1;i++) {
b=a+b;
a=b-a;
}
return b;
}
}
Have you met this question in a real interview?
Yes
本文介绍了一个经典的动态规划问题——爬楼梯问题。该问题要求计算出到达楼梯顶部的不同方式的数量,每次只能上1阶或2阶。文章提供了一种高效的解决方案,通过迭代而非递归的方式减少了重复计算。
11万+

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



