爬楼梯
题目

具体思路
斐波那契数列。
具体实现
class Solution {
public int climbStairs(int n) {
int pre = 1;
int next = 2;
if (n <= 2) {
return n;
}
int res = -1;
for (int i = 2; i < n; i++) {
res = pre + next;
pre = next;
next = res;
}
return res;
}
}
类似于爬楼梯,当前的状态取决于 n − 1 和 n − 2 的状态;只保留最终的结果,不需要使用整个数组进行保存。
class Solution {
public int climbStairs(int n) {
int[] res = new int[n + 2];
res[1] = 1;
res[2] = 2;
for (int i = 3; i <= n; i++) {
res[i] = res[i - 1] + res[i - 2];
}
return res[n];
}
}
使用数组,保存中间结果。
class Solution {
public:
int climbStairs(int n) {
if (n == 1 || n == 0)
return 1;
vector<int> dp(n + 1, 0);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
评论(0)
暂无评论