File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ // Approach 2: DFS with Memoization
2+ // 🗓️ 2025-04-06
3+ // ⏳ Time Complexity: O(n)
4+ // 💾 Space Complexity: O(n)
5+
6+ function climbStairs ( n : number ) : number {
7+ const memo = new Map < number , number > ( ) ;
8+
9+ const dfs = ( step : number ) => {
10+ if ( step > n ) return 0 ;
11+ if ( step === n ) return 1 ;
12+ if ( memo . has ( step ) ) return memo . get ( step ) ;
13+
14+ const result = dfs ( step + 1 ) + dfs ( step + 2 ) ;
15+ memo . set ( step , result ) ;
16+ return result ;
17+ } ;
18+
19+ return dfs ( 0 ) ;
20+ }
21+
22+
23+ // Approach 1: DFS (depth-first search)
24+ // ❌ Time Limit Exceeded (TLE) error!
25+ // ⏳ Time Complexity: O(2^n)
26+ // 💾 Space Complexity: O(n)
27+ // The maximum depth of the recursive call stack is n, because we go from step = 0 to step = n.
28+
29+ // function climbStairs(n: number): number {
30+ // // 1 -> 1 -> 1
31+ // // 1 -> 2
32+ // // 2 -> 1
33+
34+ // const dfs = (step: number) => {
35+ // // reach the top
36+ // if (step > n) return 0;
37+ // if (step === n) return 1;
38+
39+ // return dfs(step + 1) + dfs(step + 2);
40+ // };
41+
42+ // return dfs(0);
43+ // }
You can’t perform that action at this time.
0 commit comments