class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
return climbStairs(n - 1) + climbStairs(n - 2);
}
};
class Solution {
public:
int climbStairs(int n) {
vector<int> stepToCnt(n + 1, -1);
stepToCnt[1] = 1;
if (n == 1) {
return stepToCnt[1];
}
stepToCnt[2] = 2;
if (n == 2) {
return stepToCnt[2];
}
return dp(n, stepToCnt);
}
private:
// dp returns the number of ways for climbing to the n-th step.
int dp(int n, vector<int> &stepToCnt) {
if (stepToCnt[n] > 0) {
// We have calculated stepToCnt[n].
// Just reuse its answer.
return stepToCnt[n];
}
stepToCnt[n] = dp(n - 1, stepToCnt) + dp(n - 2, stepToCnt);
return stepToCnt[n];
}
};
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n + 1, -1);
dp[1] = 1;
if (n == 1) {
return dp[1];
}
dp[2] = 2;
if (n == 2) {
return dp[2];
}
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
class Solution {
public:
int climbStairs(int n) {
int a = 1;
if (n == 1) {
return a;
}
int b = 2;
if (n == 2) {
return b;
}
int c;
for (int i = 3; i <= n; ++i) {
c = a + b;
a = b;
b = c;
}
return c;
}
};
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up