Idea: dynamic planning solution
- Dp [I] represents the way to climb n steps.
- State transition equation DP [I] = DP [i-1] + DP [i-2]; The first is DP [i-1], i-1 stairs, there is a DP [I-1] method, then one step to jump a step is not DP [I]. There is ALSO DP [I-2], i-2 stairs, there is A DP [I-2] method, then one step to jump two steps is not DP [I]. (This is actually a Fibonacci sequence.)
- Initialize the dp []
Unoptimized code: Time complexity O(N) Space complexity O(N)
// Time complexity O(N) space complexity O(N)
class Solution {
public int climbStairs(int n) {
if (n <= 1) {// Special case handling
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];// State transition equation
}
returndp[n]; }}Copy the code
Dp [i-1] = dp[i-2] = dp[i-1] = dp[i-2] = dp[i-1] = dp[i-2] = dp[i-1]
Optimized code: time complexity O(N) Space complexity O(1)
// Time complexity O(N) space complexity O(1)
class Solution {
public int climbStairs(int n) {
if (n <= 1) {// Special case handling
return 1;
}
int p = 1;
int q = 2;
for (int i = 3; i <= n; i++) {
int r = p + q;
p = q;
q = r;
}
returnq; }}Copy the code