leetcode96 Unique Binary Search Trees

 1 """
 2 Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
 3 Example:
 4 Input: 3
 5 Output: 5
 6 Explanation:
 7 Given n = 3, there are a total of 5 unique BST's:
 8 
 9    1         3     3      2      1
10            /     /      /       
11      3     2     1      1   3      2
12     /     /                        
13    2     1         2                 3
14 """
15 """
16 数学分析,让每个值作为根结点,再讨论
17 左右子树结点的数量,能得到
18 res[1]=1
19 res[2]=res[1]*res[0]+res[0]*res[1]
20 res[3]=(res[0]*res[2])+(res[1]*res[1])+(res[2]*res[0])
21 令res[0]=1保证树的一边为空存在
22 """
23 class Solution:
24     def numTrees(self, n):
25         res = [0]*(n+1)
26         res[0], res[1] = 1, 1
27         for i in range(2, n+1):
28             for j in range(i):
29                 res[i] += res[j]*res[i-j-1]
30         return res[n]
原文地址:https://www.cnblogs.com/yawenw/p/12416547.html