zoukankan      html  css  js  c++  java
  • [LeetCode] Unique Binary Search Trees II dfs 深度搜索

    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
    

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    Hide Tags
     Tree Dynamic Programming
     
      这个嘛,对于1 to n ,如果要用某个值做节点,那么这个值左部分的全部可能的树,递归调用获得,右部分同理,这样便可以获取结果。
     
    #include <iostream>
    #include <vector>
    using namespace std;
    
    /**
     * Definition for binary tree
     */
    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) {
            return help_f(1,n);
        }
        vector<TreeNode *> help_f(int l,int r)
        {
            vector<TreeNode *> ret;
            if(l>r){
                ret.push_back(NULL);
                return ret;
            }
            for(int i=l;i<=r;i++){
                vector<TreeNode *> lPart = help_f(l,i-1);
                vector<TreeNode *> rPart = help_f(i+1,r);
                for(int lidx=0;lidx<lPart.size();lidx++){
                    for(int ridx=0;ridx<rPart.size();ridx++){
                        TreeNode * pNode = new TreeNode(i);
                        pNode->left = lPart[lidx];
                        pNode->right = rPart[ridx];
                        ret.push_back(pNode);
                    }
                }
            }
            return ret;
        }
    };
    
    int main()
    {
        return 0;
    }
  • 相关阅读:
    凝聚层次聚类
    Kmeans
    贝叶斯数据集
    将项目上传至码云(命令)
    协同过滤算法
    在阿里云Centos7.6上部署Supervisor来监控和操作各类服务
    Django笔记
    高并发
    FastDFS
    关于数据结构
  • 原文地址:https://www.cnblogs.com/Azhu/p/4240413.html
Copyright © 2011-2022 走看看