Skip to content

Commit b9fc072

Browse files
committed
[DP] Refactor solution to Climbing Stairs
1 parent 2b648e4 commit b9fc072

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

DP/ClimbingStairs.swift

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,28 @@
11
/**
22
* Question Link: https://leetcode.com/problems/climbing-stairs/
3-
* Primary idea: Dynamic Programming, use array as a cache to store calculated data
4-
* Time Complexity: O(n), Space Complexity: O(n)
3+
* Primary idea: Dynamic Programming, dp[i] = dp[i - 1] + dp[i - 2]
4+
* Time Complexity: O(n), Space Complexity: O(1)
55
*
66
*/
77

88
class ClimbingStairs {
9-
func climbStairs(n: Int) -> Int {
10-
var steps = [Int](count: n + 1, repeatedValue: 0)
11-
return _helper(n, &steps)
12-
}
13-
14-
private func _helper(n: Int, inout _ steps: [Int]) -> Int {
15-
// termination case
9+
func climbStairs(_ n: Int) -> Int {
1610
if n < 0 {
1711
return 0
1812
}
19-
if n == 0 {
13+
if n == 0 || n == 1 {
2014
return 1
2115
}
2216

23-
if steps[n] != 0 {
24-
return steps[n]
25-
}
17+
var prev = 0, post = 1, total = 0
2618

27-
steps[n] = _helper(n - 1, &steps) + _helper(n - 2, &steps)
28-
return steps[n]
19+
for i in 1...n {
20+
total = prev + post
21+
22+
prev = post
23+
post = total
24+
}
25+
26+
return total
2927
}
3028
}

0 commit comments

Comments
 (0)