LeetCode 96. Unique Binary Search Trees
96. Unique Binary Search Trees
相关链接
描述
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
例子:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
递归
BST的特征是左小右大,给定一个n,可以取1,2...n分别为根节点,假定根节点为i,其左子树的节点个数为i-1(节点为1,2···i-1),右子树的个数为n-i(节点为n+1····n)。对于一个根来说,唯一BST的个数为左子树节点数的变化个数乘以右子树的个数。
注:空树和一个节点变化数为1.
class Solution {
public:
int numTrees(int n) {
/*超时*/
if (n<=1)
return 1;
int num=0;
for (int i=1;i<=n;i++)
num += numTrees(i-1)*numTrees(n-i);
return num;
}
};
卡特兰数
设dp[n]为n个节点时的总变化数
dp[0]=dp[1]=1
dp[2]=dp[0] * dp[1] (1为根,左为NULL,右边一个节点)
+dp[1] * dp[0] (2为根,左边一个节点,右边为null)
dp[3] = dp[0] * dp[2] (1为根,则左为null,右有2个节点)
+ dp[1] * dp[1] (2为根,则左右都各有一个节点)
+ dp[2] * dp[0] (3为根,则左子有两个节点,右null)
综上 dp[0]=1
dp[n+1]=sum(dp[i] * dp[n-i]) i:0-->n
class Solution {
public:
int numTrees(int n) {
vector<int> sumNode(n+1,0);
sumNode[0]=sumNode[1]=1;
for (int i=2;i<=n;i++)
for(int j=0;j<i;j++)
sumNode[i]+=sumNode[j]*sumNode[i-j-1];
return sumNode[n];
}
};
参考
link
blogs record our growth