Skip to content

Commit 0544b80

Browse files
committed
不同的二叉查找树
1 parent 122b2b8 commit 0544b80

File tree

1 file changed

+9
-20
lines changed

1 file changed

+9
-20
lines changed

unique_binary_search_trees.py

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,14 @@
1-
# -*- coding: utf-8 -*-
2-
31
class Solution:
4-
def __init__(self):
5-
self.cache = {}
6-
72
# @paramn n: An integer
83
# @return: An integer
94
def numTrees(self, n):
10-
if n <= 1:
5+
# write your code here
6+
# 只需要计算数量,不需要计算每棵树的形状,所以缓存结果就可以了。
7+
if n == 0:
118
return 1
12-
else:
13-
if n in self.cache:
14-
return self.cache[n]
15-
else:
16-
sum = 0
17-
for i in xrange(1, n + 1):
18-
left_num, right_num = 1, 1
19-
if i > 0:
20-
left_num = self.numTrees(i - 1) # 计算左子树数量
21-
if i < n:
22-
right_num = self.numTrees(n - i) # 计算右子树数量
23-
sum += left_num * right_num
24-
self.cache[n] = sum
25-
return self.cache[n]
9+
methods = [0] * (n + 1)
10+
methods[0], methods[1] = 1, 1
11+
for i in xrange(2, n + 1):
12+
for j in xrange(1, i + 1):
13+
methods[i] += methods[j - 1] * methods[i - j]
14+
return methods[-1]

0 commit comments

Comments
 (0)