码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-27 20:22:28      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:style   blog   os   io   strong   for   ar   art   div   

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);
    }
};

 

           

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

标签:style   blog   os   io   strong   for   ar   art   div   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3940182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!