File tree Expand file tree Collapse file tree 1 file changed +71
-1
lines changed
Expand file tree Collapse file tree 1 file changed +71
-1
lines changed Original file line number Diff line number Diff line change 1- test
1+ # Top Down Recursive
2+
3+ # Time: O(2^n)
4+ # Space: O(n)
5+ class Solution :
6+ def fib (self , n : int ) -> int :
7+ if n == 0 :
8+ return 0
9+ elif n == 1 :
10+ return 1
11+ else :
12+ return self .fib (n - 1 ) + self .fib (n - 2 )
13+
14+
15+ # Top Down Memoized
16+
17+ # Time: O(n)
18+ # Space: O(n)
19+ class Solution :
20+ def fib (self , n : int ) -> int :
21+ memo = {0 :0 , 1 :1 }
22+
23+ def f (x ):
24+ if x in memo :
25+ return memo [x ]
26+ else :
27+ memo [x ] = f (x - 1 ) + f (x - 2 )
28+ return memo [x ]
29+
30+ return f (n )
31+
32+
33+ # Bottom Up Tabulation
34+
35+ # Time: O(n)
36+ # Space: O(n)
37+ class Solution :
38+ def fib (self , n : int ) -> int :
39+ if n == 0 :
40+ return 0
41+ if n == 1 :
42+ return 1
43+
44+ dp = [0 ] * (n + 1 )
45+ dp [0 ] = 0
46+ dp [1 ] = 1
47+
48+ for i in range (2 , n + 1 ):
49+ dp [i ] = dp [i - 2 ] + dp [i - 1 ]
50+
51+ return dp [n ]
52+
53+
54+ # Bottom Up Constant Space
55+
56+ # Time: O(n)
57+ # Space: O(1)
58+ class Solution :
59+ def fib (self , n : int ) -> int :
60+ if n == 0 :
61+ return 0
62+ if n == 1 :
63+ return 1
64+
65+ prev = 0
66+ cur = 1
67+
68+ for i in range (2 , n + 1 ):
69+ prev , cur = cur , prev + cur
70+
71+ return cur
You can’t perform that action at this time.
0 commit comments