96. Unique Binary Search Trees
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
Given n = 3, there are a total of 5 unique BST’s.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
表示不会,规律无从发现。
Reference:
http://blog.csdn.net/jiadebin890724/article/details/23305915
对应左右子树情况相乘,得到结果。
后续:
卡特兰数。
介绍的很详细,后来还发现这个出栈问题原来是卡特兰数。
程序员必知(五):卡特兰数
http://blog.csdn.net/hongchangfirst/article/details/8766529
12个高矮不同的人,排成两排/Catalan数
http://blog.csdn.net/jiyanfeng1/article/details/8036007
里面把排列人转换成了入栈出栈问题。有1前必有0。有必要记住表达式。
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + … + h(n-1)h(0) (n>=2)
递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=0,1,2,…)
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1);//一组卡特兰数
dp[0]=1;
for(int i=1;i<n+1;++i)
{
if(i<3) dp[i]=i;
else
for(int j=0;j<i;++j)
{
//左子树可能(j个节点)*右子树可能(i-j-1个)
dp[i]+=dp[j]*dp[i-j-1];
}
}
return dp[n];
}
};
95. Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1…n.
For example,
Given n = 3, your program should return all 5 unique BST’s shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
这种情况我们要从下往上树生成,如果从上往下会是回溯的方法,有树的拷贝问题。根据上题的性质来解此题会有些思路,不要跑偏。但是我为什么就写不出来呢。
当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性:
以i为根节点的树,其左子树由[1, i-1]构成, 其右子树由[i+1, n]构成。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res{};
if(!n) return res;
return generateTrees(1,n);
}
private:
vector<TreeNode*> generateTrees(int beg,int end)
{
vector<TreeNode*> res{};
if(beg>end)
{
res.push_back(nullptr);
return res;
}
TreeNode *root;
for(int i=beg;i<=end;++i)
{
//左右子树多种
vector<TreeNode*> left=generateTrees(beg,i-1),right=generateTrees(i+1,end);
for(int k=0;k<left.size();++k)
{
for(int j=0;j<right.size();++j)
{
//组合多种情况
root=new TreeNode(i);
root->left=left[k];
root->right=right[j];
res.push_back(root);
}
}
}
return res;
}
};