-
Notifications
You must be signed in to change notification settings - Fork 892
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[DP] Refactor solution to Climbing Stairs
- Loading branch information
Showing
1 changed file
with
13 additions
and
15 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 |
---|---|---|
@@ -1,30 +1,28 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/climbing-stairs/ | ||
* Primary idea: Dynamic Programming, use array as a cache to store calculated data | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2] | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
* | ||
*/ | ||
|
||
class ClimbingStairs { | ||
func climbStairs(n: Int) -> Int { | ||
var steps = [Int](count: n + 1, repeatedValue: 0) | ||
return _helper(n, &steps) | ||
} | ||
|
||
private func _helper(n: Int, inout _ steps: [Int]) -> Int { | ||
// termination case | ||
func climbStairs(_ n: Int) -> Int { | ||
if n < 0 { | ||
return 0 | ||
} | ||
if n == 0 { | ||
if n == 0 || n == 1 { | ||
return 1 | ||
} | ||
|
||
if steps[n] != 0 { | ||
return steps[n] | ||
} | ||
var prev = 0, post = 1, total = 0 | ||
|
||
steps[n] = _helper(n - 1, &steps) + _helper(n - 2, &steps) | ||
return steps[n] | ||
for i in 1...n { | ||
total = prev + post | ||
|
||
prev = post | ||
post = total | ||
} | ||
|
||
return total | ||
} | ||
} |