File tree Expand file tree Collapse file tree 1 file changed +13
-15
lines changed Expand file tree Collapse file tree 1 file changed +13
-15
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
* 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 )
5
5
*
6
6
*/
7
7
8
8
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 {
16
10
if n < 0 {
17
11
return 0
18
12
}
19
- if n == 0 {
13
+ if n == 0 || n == 1 {
20
14
return 1
21
15
}
22
16
23
- if steps [ n] != 0 {
24
- return steps [ n]
25
- }
17
+ var prev = 0 , post = 1 , total = 0
26
18
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
29
27
}
30
28
}
You can’t perform that action at this time.
0 commit comments