• 41. Unique Binary Search Trees && Unique Binary Search Trees II


    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
    
    思路: f(n) = Σi=1n f(n-i)*f(i-1), 其中 f(0) = f(1) = 1; 利用动归记下之前的 f(2)~f(n-1)即可。
    class Solution {
    public:
        int numTrees(int n) {
            vector<int> f(n+1, 0);
            f[0] = f[1] = 1;
            for(int v = 2; v <= n; ++v) 
                for(int pos = 1; pos <= v; ++pos)
                    f[v] += f[pos-1] * f[v-pos];
            return f[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
    
    思路:分别以 1~n 为根节点,左右子树根的集合数量相乘,递归,依次得出结果。
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    vector<TreeNode *> generateTreesCore(int start, int end) {
        vector<TreeNode *> vec;
        if(start > end) { vec.push_back(NULL); return vec; }
        for(int cur = start; cur <= end; ++cur) {
            vector<TreeNode *> left = generateTreesCore(start, cur-1);
            vector<TreeNode *> right = generateTreesCore(cur+1, end);
            for(size_t i = 0; i < left.size(); ++i) {
                for(size_t j = 0; j < right.size(); ++j) {
                    TreeNode *root = new TreeNode(cur);
                    root->left = left[i];
                    root->right = right[j];
                    vec.push_back(root);
                }
            }
        }
        return vec;
    }
    class Solution {
    public:
        vector<TreeNode *> generateTrees(int n) {
            return generateTreesCore(1, n);
        }
    };
    
               
  • 相关阅读:
    解决clickonce不支持administer权限问题
    好好了解一下Cookie(强烈推荐)
    Cookie的存储读取删除修改 (cookie.Expires读取永远是零时间)
    14VUE插槽
    13VUE非父子组件传值
    1VUE学习方法
    11VUE监听原生事件
    10VUE,组件参数校验,组件3
    9,Vue组件2
    8.VUE计数器,基于组件
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3940182.html
Copyright © 2020-2023  润新知