2.2 KiB
Leetcode Climbing-Chairs
2022-07-20 14:37
Algorithms:
#algorithm #dynamic_programming
Difficulty:
#coding_problems #difficulty_easy
Additional tags:
#leetcode
Revisions:
N/A
Related topics:
Links:
Problem
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?
Examples
Example 1:
Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
Constraints
1 <= n <= 45
Thoughts
[!summary] This is a #dynamic_programming problem. our solution relies on other solutions
I had come up with an recursive solution, with a little bit of optimizations.
First iteration:
Base case:
-
n is 0, 1, 2: return n
Pseudo code: answer = climb(n - 1) + climb(n - 2);
This is a brute force-y solution, because there are too much combinations, and we are re-calculating solutions.
Second iteration:
Base case:
-
n = 1, 2, 3 Return n
Note that n == 3 is added, because we will calculate n - 3, which otherwise will make n = 0
and when n == 0, it should return 1.
[!tips] Optimization We can optimize it because some solutions can be calculated and used for both 1 step and 2 steps.
how many ways to climb: one step or two steps 1 + 1 = 2 0 + 2 = 2 1 + 2 = 3 -> 2 x climb two steps, and 1 x climb 3 steps
Solution
Optimized version:
class Solution {
public:
int climbStairs(int n) {
// Dymanic programming, using solution from the past
// Recursive, base case: n == 0, 1, 2, 3
if (n <= 3) {
return n;
}
// how many ways to climb: one step or two steps
// 1 + 1 = 2
// 0 + 2 = 2
// 1 + 2 = 3
// -> 2 * climb two steps, and 1 * climb 3 steps
return 2 * climbStairs(n - 2) + climbStairs(n - 3);
}
};