Created
August 5, 2023 12:49
-
-
Save optimistiks/791c4b1e531aceb3cd0a295c100a60e7 to your computer and use it in GitHub Desktop.
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function climbStairs(nums) { | |
| const dp = Array.from(nums).fill(0); | |
| dp[0] = 1; | |
| dp[1] = 1; | |
| // ways to reach step i = ways to reach step i-1 + ways to reach step i-2 | |
| for (let i = 2; i <= nums; ++i) { | |
| dp[i] = dp[i - 1] + dp[i - 2]; | |
| } | |
| return dp[nums]; | |
| } | |
| // tc: O(n) (can be improved with another approach to O(logn)) | |
| // sc: O(n) (can be improved to O(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment