Unique Binary Search Trees I&II——给定n有多少种BST可能、DP

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
注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
 
分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i  的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
 1 class Solution {
 2 public:
 3     int numTrees(int n) {
 4         vector<int> v(n+1,0);
 5         if(n<3) return n;
 6         v[0]=1;
 7         for(int i=1;i<=n;i++){
 8             if(i<3){
 9                 v[i]=i;
10                 continue;
11             }
12             for(int j=1;j<=i;j++){
13                 v[i]+=v[j-1]*v[i-j];
14             }
15         }
16         return v[n];
17     }
18 };

II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

 

递归获取left——right的所有可能树,并存在vector中,以供上一层取值

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<TreeNode *> generateTrees(int n) {
13         return sol(1,n);
14     }
15     vector<TreeNode *> sol(int left, int right){
16         vector<TreeNode *> res; //保障res只会输出当前获取的树
17         if(left>right){
18             res.push_back(NULL);  //否则返回后取值时会得到野指针
19             return res;
20         }
21             
22         for(int i=left;i<=right;i++){
23             vector<TreeNode *> leftlist=sol(left,i-1);
24             vector<TreeNode *> rightlist=sol(i+1,right);
25             for(int j=0;j<leftlist.size();j++){
26                 for(int k=0;k<rightlist.size();k++){
27                     TreeNode *root=new TreeNode(i);
28                     root->left=leftlist[j];
29                     root->right=rightlist[k];
30                     res.push_back(root);
31                 }
32             }
33         }
34         return res;
35     }
36     
37 };

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值