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
https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i
如果F(n)表示长度为n的二叉树有多少种结果,则
F(n) = F(0)*F(n-1) + F(1)*F(n-2) + F(2)*F(n-2) + ......+ F(n-1)*F(0)
所以代码如下:
class Solution {
public:
int numTrees(int n) {
if(n <= 0) return 0;
vector<int> nums(n+1,0);
nums[0] = 1;
for(int i = 1; i<=n; i++){
for(int j = 1; j <=i ; j++){
nums[i] += nums[j-1]*nums[i-j];
}
}
return nums[n];
}
};
Unique Binary Search Trees II
Given 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
同样沿用 I 的思路,利用分治思想
/**
* 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) {
if(n <=0) return vector<TreeNode*>();
return generateSubTrees(1,n);
}
vector<TreeNode*>generateSubTrees(int s,int e){
vector<TreeNode*> res;
if(s > e){
res.push_back(NULL);
return res;
}
for(int i = s; i <= e;i++ ){
vector<TreeNode*> left = generateSubTrees(s,i-1);
vector<TreeNode*> right = generateSubTrees(i+1,e);
for(auto l : left){
for(auto r : right){
TreeNode* root = new TreeNode(i);
root->left = l;
root->right = r;
res.push_back(root);
}
}
}
return res;
}
};