leetcode96 Unique Binary Search Trees

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]

 

以上是关于leetcode96 Unique Binary Search Trees的主要内容,如果未能解决你的问题,请参考以下文章

Java [Leetcode 96]Unique Binary Search Trees

[动态规划] leetcode 96 Unique Binary Search Trees

Leetcode 96. Unique Binary Search Trees

Leetcode 96. Unique Binary Search Trees

LeetCode 96:Unique Binary Search Trees

leetcode96 Unique Binary Search Trees