https://github.com/emahtab/climbing-stairs
Climbing Stairs
https://github.com/emahtab/climbing-stairs
climbing-stairs dynamic-programming leetcode problem-solving
Last synced: 3 months ago
JSON representation
Climbing Stairs
- Host: GitHub
- URL: https://github.com/emahtab/climbing-stairs
- Owner: eMahtab
- Created: 2019-12-21T03:11:10.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-01-16T09:17:19.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:26:14.120Z (5 months ago)
- Topics: climbing-stairs, dynamic-programming, leetcode, problem-solving
- Language: Java
- Size: 10.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?Note: Given n will be a positive integer.
```
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 stepsExample 2:
Input: 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
```
### Implementation :#### Dynamic Programming
```java
public class App {
public static void main(String[] args) {
System.out.println("Total ways to climb 3 stairs: "+climbStairs(3));
}
// Runtime = O(n) , Space = O(n)
private static int climbStairs(int n) {
int[] dpTable = new int[n+1];
dpTable[0] = 1;
dpTable[1] = 1;
for(int i = 2; i <= n; i++){
dpTable[i] = dpTable[i-1] + dpTable[i-2];
}
return dpTable[n];
}
}```
The above implementation have both runtime and space complexity of O(n)
```
Runtime Complexity = O(n)
Space Complexity = O(n)
```#### Dynamic Programming - Space Optimization O(1)
```java
public class App {
public static void main(String[] args) {
System.out.println("Total ways to climb 3 stairs: "+climbStairs(3));
}
// Runtime = O(n) , Space = O(1)
private static int climbStairs(int n) {
int oneStairBefore = 1;
int twoStairsBefore = 1;
int nthStair = 1;
for(int i = 2; i <= n; i++){
nthStair = oneStairBefore + twoStairsBefore;
twoStairsBefore = oneStairBefore;
oneStairBefore = nthStair;
}
return nthStair;
}
}
```The above implementation have runtime complexity of O(n) and space complexity of O(1)
```
Runtime Complexity = O(n)
Space Complexity = O(1)
```