zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    浏览器跨域访问WebApi
    外部主机无法访问IIS发布的网站
    在VisualStudio中远程调试IIS站点
    关于跨域请求的一些解决方案
    MVC与WebApi中的异常过滤器
    委托与事件
    C#中的属性
    C#中的索引
    Equals与==的区别
    关于跨域响应头Access-Control-Allow-Headers的一些说明
  • 原文地址:https://www.cnblogs.com/zl1991/p/7056646.html
Copyright © 2011-2022 走看看