Skip to content

Commit 77d1003

Browse files
committed
regular leetcode
1 parent 06fc6c6 commit 77d1003

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

096._unique_binary_search_trees.md

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
###96. Unique Binary Search Trees
2+
3+
4+
5+
题目:
6+
<https://leetcode.com/problems/unique-binary-search-trees/>
7+
8+
9+
难度:
10+
Medium
11+
12+
思路:
13+
14+
15+
参照此处hint:
16+
17+
<https://shenjie1993.gitbooks.io/leetcode-python/content/096%20Unique%20Binary%20Search%20Trees.html>
18+
19+
20+
首先明确n个不等的数它们能构成的二叉搜索树的种类都是相等的.
21+
22+
毫无头绪,对于1...n的bst,可以这样看,k可以作为root,那么1..k-1必定在左边,k+1...n必定在右边,而1...k-1课产生的bst树是dp[k-1],右边产生的数是dp[n-k],所以能生成的树的数量是 dp[k-1]* dp[n-k]
23+
24+
dp[n] = sum(dp[k-1]*dp[n-k]),从0到k
25+
26+
27+
```
28+
class Solution(object):
29+
def numTrees(self, n):
30+
"""
31+
:type n: int
32+
:rtype: int
33+
"""
34+
dp = [ 1 for i in range(n+1)]
35+
36+
for i in range(2,n+1):
37+
s = 0
38+
for k in range(i):
39+
s += dp[k]*dp[i-k-1]
40+
dp[i] = s
41+
42+
return dp[-1]
43+
```

0 commit comments

Comments
 (0)