leetcode--Unique Binary Search Trees

来源:互联网 发布:apache 压力测试工具 编辑:程序博客网 时间:2024/06/06 09:51

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


思路:有点类似斐波那契数列。

class Solution {public:    int numTrees(int n) {        if(n<=0)return 0;        int tmp[n+1]={0};        tmp[0] = 1;        tmp[1] = 1;        for(int i=2;i<=n;i++)        {            for(int j=0;j<i;j++)            {                tmp[i] += tmp[j]*tmp[i-j-1];            }        }        return tmp[n];     }};或者class Solution {private:    vector<TreeNode*> helper(int start, int end){        vector<TreeNode*> res;        if(start > end) {            res.push_back(NULL);            return res;        }        for(int i = start; i <= end; i++){            vector<TreeNode*> lefts = helper(start, i - 1);            vector<TreeNode*> rights = helper(i + 1, end);            for(int j = 0; j < (int)lefts.size(); j++){                for(int k = 0; k < (int)rights.size(); k++){                    TreeNode* root = new TreeNode(i);                    root->left = lefts[j];                    root->right = rights[k];                    res.push_back(root);                }            }        }        return res;    }public:    vector<TreeNode*> generateTrees(int n) {        if(n == 0) return vector<TreeNode*>(0);        return helper(1,n);    }};
0 0
原创粉丝点击