LeetCode-70. Climbing Stairshttps://leetcode.com/problems/climbing-stairs/
题目描述
You are climbing a staircase. It takes?n ?steps to reach the top.
Each time you can either climb?1 ?or?2 ?steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
解题思路
【C++】
1. 动态规划
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {return n;}
vector<int> dp(n + 1, 1);
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
2. 空间压缩的动态规划
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {return n;}
int pre2 = 1, pre1 = 2, cur;
for (int i = 3; i <= n; i++) {
cur = pre1 + pre2;
pre2 = pre1;
pre1 = cur;
}
return cur;
}
};
【Java】
1. 动态规划
class Solution {
public int climbStairs(int n) {
if (n <= 2) {return n;}
int[] dp = new int[n + 1];
Arrays.fill(dp, 1);
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
}
2. 压缩空间的动态规划
class Solution {
public int climbStairs(int n) {
if (n <= 2) {return n;}
int pre2 = 1, pre1 = 2, cur = 0; //必须初始化
for (int i = 3; i <= n; i++) {
cur = pre1 + pre2;
pre2 = pre1;
pre1 = cur;
}
return cur;
}
}
|