LeetCode

来源:互联网 发布:阿里云大厦今日头条 编辑:程序博客网 时间:2024/06/05 04:53

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
给定一个数n,求1到n这些数可以构成多少棵二叉树。

给定一个序列1~n,为了构造所有二叉树,我们可以使用1~n中的每一个数i作为根节点,自然1~(i-1)必然位于树的左子树中,(i+1)~n位于树的右子树中。然后可以递归来构建左右子树,由于根节点是唯一的,所以可以保证构建的二叉树都是唯一的。

使用两个状态来记录:

G(n):长度为n的序列的所有唯一的二叉树。

F(i, n),1<=i<=n:以i作为根节点的二叉树的数量。

G(n)就是我们要求解的答案,G(n)可以由F(i,n)计算而来。

G(n)=F(1,n)+F(2,n)+...+F(n,n)                      (1)

G(0)=1,G(1)=1

对于给定的一个序列1.....n,我们取i作为它的根节点,那么以i作为根节点的二叉树的数量F(i)可以由下面的公式计算而来:

F(i,n)=G(i-1)*G(n-i) 1<=i<=n                         (2)

综合公式(1)和公式(2),可以看出:

G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)

这就是上面这个问题的答案。

时间复杂度O(n^2),空间复杂度O(n)

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




95. Unique Binary Search Trees II

Given an integer 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
将上题构造的二叉树都输出。

当前的递归中,假设root为i。那么显然左子树是由[1,i-1]构成的所有可能的组合,显然右子树是由[i+1,n]构成的所有可能的组合(可以统一记录为,用[start, end]去构建树)。在有了左子树,root,右子树的情况下,根据乘法原理很容易计算得出在当前情况下的所有的树。记录root到一个vector中就可以完整地记录所有结果。返回结果即可。

/** * 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) {        if (!n) return vector<TreeNode*> {};        return solve(1, n);    }        vector<TreeNode*> solve(int st, int ed) {        if (st > ed) return vector<TreeNode*> {NULL};                vector<TreeNode*> ans;        for (int i = st; i <= ed; ++i) {            vector<TreeNode*> le = solve(st, i - 1);            vector<TreeNode*> ri = solve(i + 1, ed);            for (int j = 0; j < le.size(); ++j) {                for (int k = 0; k < ri.size(); ++k) {                    TreeNode* cur = new TreeNode(i);                    cur->left = le[j];                    cur->right = ri[k];                    ans.push_back(cur);                }            }        }        return ans;    }};