problem
solution
option 1
1 | class Solution { |
- recursive version => time out
1
2
3
4
5
6
7
8class Solution {
public:
int climbStairs(int n) {
if(n<3) return n;
return climbStairs(n-1)+climbStairs(n-2);
}
}; - optimal recursive version
使用 hash table 紀錄已經call 過的function(),避免重複運算
1 | class Solution { |
option 2 - reduce space
1 | class Solution { |
analysis
- option 1
- time complexity
O(n)
- space complexity
O(n)
- time complexity
- option 2
- time complexity
O(n)
- space complexity
O(1)
- time complexity