-
Notifications
You must be signed in to change notification settings - Fork 0
/
_96.py
55 lines (38 loc) · 910 Bytes
/
_96.py
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
# -*- coding: utf-8 -*-
__author__ = 'gzp'
class Solution1:
cache = {}
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n in self.cache.keys():
return self.cache[n]
if n == 0:
return 1
if n <= 2:
return n
res = 0
for i in range(n):
res += self.numTrees(i) * self.numTrees(n - i - 1)
self.cache[n] = res
return res
class Solution2:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = {0: 1}
for i in range(1, n + 1):
res = 0
for j in range(i):
res += dp[j] * dp[i - j - 1]
dp[i] = res
return dp[n]
if __name__ == '__main__':
# s = Solution1()
# print(s.numTrees(3))
s = Solution2()
print(s.numTrees(3))