LeetCode 70. Climbing Stairs [Easy]

题目来源:https://leetcode.com/problems/climbing-stairs

题目难度:Easy

解答1[Java]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public int climbStairs(int n) {
if (n == 1) {
return 1;
}
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}

思路

动态规划。

解答2[Java]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public int climbStairs(int n) {
if (n == 1) {
return 1;
}
int first = 1;
int second = 2;
for (int i = 3; i <= n; i++) {
int third = first + second;
first = second;
second = third;
}
return second;
}
}

思路

斐波那契数。

比上一个算法优化的地方在于空间复杂度由 $O(n)$ 变为 $O(1)$。