-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0096_unique_binary_search_trees.py
More file actions
100 lines (81 loc) · 2.24 KB
/
0096_unique_binary_search_trees.py
File metadata and controls
100 lines (81 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#------------------------------------------------------------------------------
# Question: 0096_unique_binary_search_trees.py
#------------------------------------------------------------------------------
# tags: #trees #medium
'''
Given n, how many structurally unique BST's (binary search trees) that store
values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
4
/ \
2 5
/ \ \
1 3 6
\
7
1234 5 67890
r
L = numTrees(i-1)
R = numTrees(n-i)
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
from test_utils.debug import debug
class SolutionDFS:
'''
Time: O(n^2)
Space: O(1)
'''
# @debug
def numTrees(self, n: int) -> int:
if n <= 1:
return 1
res = 0
for i in range(1, n + 1):
left = self.numTrees(i - 1)
right = self.numTrees(n - i)
res += left*right
return res
class SolutionDP:
'''
Time:O(n^2)
Space:O(n)
'''
def numTrees(self, n: int) -> int:
if n <= 1:
return 1
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for n in range(2, n + 1):
for i in range(1, n +1):
left = dp[i - 1]
right = dp[n - i]
dp[n] += left * right
return dp[-1]
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = SolutionDFS()
self.assertEqual(s.numTrees(3), 5)
s = SolutionDP()
self.assertEqual(s.numTrees(3), 5)
def test_one(self):
s = SolutionDFS()
self.assertEqual(s.numTrees(1), 1)
s = SolutionDP()
self.assertEqual(s.numTrees(1), 1)
unittest.main(verbosity=2)