leetcode 95-96: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
如果集合为空,只有一种BST,即空树,
UniqueTrees[0] =1

如果集合仅有一个元素,只有一种BST,即为单个节点
UniqueTrees[1] = 1

 

UniqueTrees[2] = UniqueTrees[0] * UniqueTrees[1]   (1为根的情况)
                  + UniqueTrees[1] * UniqueTrees[0]  (2为根的情况。

再看一遍三个元素的数组,可以发现BST的取值方式如下:
UniqueTrees[3] = UniqueTrees[0]*UniqueTrees[2]  (1为根的情况:左边0个结点,右边2个结点)
               + UniqueTrees[1]*UniqueTrees[1]  (2为根的情况:左边1个结点,右边1个结点)
               + UniqueTrees[2]*UniqueTrees[0]  (3为根的情况:左边2个结点,右边0个结点)

所以,由此观察,可以得出UniqueTrees的递推公式为
UniqueTrees[i] = ∑ UniqueTrees[0...k] * [i-1-k]     k取值范围 0<= k <=(i-1)

class Solution {
public:
    int numTrees(int n) {
        vector<int> flg(n+1,0);
        flg[0]=1;
        flg[1]=1;
        for(int i=2;i<=n;i++){
            for(int k=0;k<=i-1;k++){
                flg[i]+=flg[k]*flg[i-1-k];
            }
        }
        return flg[n];
    }
};

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.

/**
 * Definition for a binary tree node.
 * 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 creatTree(1,n);
    }
    vector<TreeNode*> creatTree(int start,int end){
        vector<TreeNode*> ret;
        if(start>end){
            ret.push_back(NULL);
            return ret;
        }
        for(int i=start;i<=end;i++){
            vector<TreeNode*> left=creatTree(start,i-1);// 生成n多棵左树
            vector<TreeNode*> right=creatTree(i+1,end);// 生成n多棵右树
            for(int j=0;j<left.size();j++){
                for(int k=0;k<right.size();k++){
                    TreeNode* root=new TreeNode(i);
                    root->left=left[j];
                    root->right=right[k];
                    ret.push_back(root);
                }
            }
        }
        return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值