File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
Expand file tree Collapse file tree 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import Dict
2+
3+
4+ class Solution :
5+ # Time: O(n)
6+ # Space: O(n)
7+ # ---
8+ # 1. Prepare a table for caching. Initially put trivial answers for n = 1, 2.
9+ # Space: O(n)
10+ cacheTableOfAnswerByN : Dict [int , int ] = {1 : 1 , 2 : 2 }
11+
12+ def climbStairs (self , n : int ) -> int :
13+ # 2. Use caching.
14+ # Time: O(1)
15+ try : return self .cacheTableOfAnswerByN [n ]
16+ except KeyError :
17+ # 3. Simply, the answers follow Fibonacci sequence. Use recursion.
18+ # O(n)
19+ answerBeforeTwoSteps = self .climbStairs (n - 2 )
20+ # 4. Cache the answer during recursion.
21+ self .cacheTableOfAnswerByN [n - 2 ] = answerBeforeTwoSteps
22+ answerBeforeOneStep = self .climbStairs (n - 1 )
23+ self .cacheTableOfAnswerByN [n - 1 ] = answerBeforeOneStep
24+ return answerBeforeTwoSteps + answerBeforeOneStep
You can’t perform that action at this time.
0 commit comments