Algorithm
Problem Name: 70. 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:
1 <= n <= 45
Code Examples
#1 Code Example with C Programming
Code -
C Programming
int climbStairs(int n) {
int p, pp, k, i;
if (n == 1) return 1;
if (n == 2) return 2;
p = 2;
pp = 1;
for (i = 3; i < = n; i++) {
k = p + pp;
pp = p;
p = k;
}
return p;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int climbStairs(int n) {
vector<int>dp(n + 1);
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i < n + 1; i++)
dp[i] = dp[i - 1] + dp[i - 2];
return dp[n];
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
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];
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const climbStairs = function(n) {
const hash = {};
return single(n, hash);
};
function single(i, hash) {
if (hash.hasOwnProperty(i)) {
return hash[i];
}
if (i === 1) {
hash[1] = 1;
return 1;
}
if (i === 2) {
hash[2] = 2;
return 2;
}
hash[i] = single(i - 1, hash) + single(i - 2, hash);
return hash[i];
}
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def climbStairs(self, n: int) -> int:
memo = {}
def dfs(i):
if i >= n: return 1 if i == n else 0
if i not in memo:
memo[i] = dfs(i + 1) + dfs(i + 2)
return memo[i]
return dfs(0)
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _070_ClimbingStairs
{
public int ClimbStairs(int n)
{
if (n < 4) { return n; }
int x1 = 2, x2 = 3, temp;
for (int i = 4; i < = n; i++)
{
temp = x1 + x2;
x1 = x2;
x2 = temp;
}
return x2;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output