zoukankan      html  css  js  c++  java
  • LeetCode 95. Unique Binary Search Trees II

    原题链接在这里:https://leetcode.com/problems/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

    题解:

    Unique Binary Search Trees的进阶版本. 返回的不是个数,而是每一个结果。

    对于i在[1,n]区间内, 以i为root时, 生成BST的left child 是由1到i-1生成的, BST的right child 是由i+1 到n生成的.

    recursive call先得到左右子树分别的所有结果.

    然后从左右子树的返回结果中依次取点,接到有 i 生成的root上,一共有m*n种接法。构造好后当前root加到res里.

    recursive call的 stop condition是l>r. 此时没有i能存在[l, r]这个区间内. 加上null节点.

    可行的BST数量是卡特兰数,不是多项式时间,所以要求解所有结果也不是在多项式时间内可以完成的。

    Time Complexity: O(catalan number), exponential.

    Space: O(n). 开了n层stack.

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<TreeNode> generateTrees(int n) {
    12         List<TreeNode> res = new ArrayList<TreeNode>();
    13         if(n<1){
    14             return res;
    15         }
    16         
    17         return helper(1,n);
    18     }
    19     
    20     private List<TreeNode> helper(int left, int right){
    21         List<TreeNode> res = new ArrayList<TreeNode>();
    22         if(left > right){
    23             res.add(null);
    24             return res;
    25         }
    26         
    27         for(int i = left; i<=right; i++){
    28             List<TreeNode> leftRes = helper(left,i-1);
    29             List<TreeNode> rightRes = helper(i+1, right);
    30             //从leftRes中挨个取结果,配合从rightRes中挨个取结果后分别放在以i为root的左右子树上
    31             for(int m = 0; m<leftRes.size(); m++){
    32                 for(int n = 0; n<rightRes.size(); n++){
    33                     TreeNode root = new TreeNode(i);
    34                     root.left = leftRes.get(m);
    35                     root.right = rightRes.get(n);
    36                     res.add(root);
    37                 }
    38             }
    39         }
    40         return res;
    41     }
    42 }

    类似Different Ways to Add Parentheses.

  • 相关阅读:
    JAVA火星坐标系、百度坐标系、84坐标系相互转换工具类
    MySQL查看数据库连接数
    GmSSL制作国密算法自签证书和 HTTPS 配置
    mysql占用内存过多
    Redis 缓存穿透、击穿、雪崩
    Linux清理入侵痕迹
    helm v3
    docker常见的网络
    fuser、lsof的使用
    find命令-exec选项,find命令配合xargs
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824971.html
Copyright © 2011-2022 走看看