-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# 70. Climbing Stairs | ||
|
||
`Easy` | ||
|
||
## Description | ||
|
||
<p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p> | ||
|
||
<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p> | ||
|
||
## My thought | ||
|
||
steps to 5 equals `step 3 combinations + 2 steps `or `step 3 combiations + 1 step`. | ||
|
||
So we can create a DP `f(n) = f(n-1) + f(n-2)` | ||
There is two way | ||
|
||
1. Recursive from the end. | ||
2. Store steps spend into an array and loop from step 3 to end, plus previous steps and more previous steps. | ||
`To save more menmory, we can just store 2 steps previous without whole route` | ||
|
||
## O(N) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
// solution1 | ||
function climbStairs(n: number): number { | ||
let stairs:number[] = new Array(); | ||
stairs[1] = 1; | ||
stairs[2] = 2; | ||
|
||
for(let i = 3; i<=n;i++){ | ||
stairs[i] = stairs[i-1] + stairs[i-2]; | ||
} | ||
return stairs[n]; | ||
}; | ||
// solution2 | ||
function climbStairs(n: number): number { | ||
if (n==1) return 1; | ||
if (n==2) return 2; | ||
|
||
let oneStepBefore = 2; | ||
let twoStepBefore = 1; | ||
let ans = 2; | ||
for(let i = 3; i<=n;i++){ | ||
ans = oneStepBefore + twoStepBefore; | ||
let temp = oneStepBefore; | ||
oneStepBefore = ans; | ||
twoStepBefore = temp; | ||
} | ||
return ans; | ||
}; |