Unique Binary Search Trees
Problem
Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
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
Note
对于这种找解的个数的题目,可以用DP来做。
这道题用DP的思路是,建立count[]数组,存放从1到n每一个数对应的BST的个数。
对于数n,可能有多少个BST呢?这个是由它的根节点分布决定的,若根节点为root,左子树的个数就是count[root-1]的值,右子树的个数就是count[i-root]的值,两个解的乘积就是根节点为root,借点总数为i的所有BST的个数。将root从1到i遍历一遍,就得到了count[i],即i个结点的所有解。DP到count[n]即为所求n个结点的所有BST总数。
Solution
public class Solution {
public int numTrees(int n) {
int[] count = new int[n+1];
count[0] = 1;
for (int i = 1; i <= n; i++) {
for (int root = 1; root <= i; root++) {
int left = count[root-1];
int right = count[i-root];
count[i] += left*right;
}
}
return count[n];
}
}
Unique Binary Search Trees II
Problem
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
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
Note
首先,重新构建class。我们在helper()
函数中增加start
和end
两个参数,以便更好地使用递归操作。和Unique BST I一样,仍然考虑root
从1到n,每种情况下限定左右子树,以对res
进行更新。
注意两点:
限定左右子树的写法:对于
root.val = i
,左右子树分别来自于集合helper(start, i-1)
和helper(i+1, end)
,要用Enhanced for loop进行遍历。在两个for循环内部,左右子树都已被确定,此时要将它们与root进行连接,其实并不需要copy()函数来复制已经选择好的左右子树
nodeLeft
和nodeRight
。
Solution
public class Solution {
public List<TreeNode> generateTrees(int n) {
return helper(1, n);
}
public List<TreeNode> helper(int start, int end) {
List<TreeNode> res = new ArrayList<TreeNode>();
if (start > end) {
res.add(null);
return res;
}
for (int i = start; i <= end; i++) {
List<TreeNode> left = helper(start, i-1);
List<TreeNode> right = helper(i+1, end);
for (TreeNode rootLeft: left) {
for (TreeNode rootRight: right) {
TreeNode root = new TreeNode(i);
root.left = copy(rootLeft);
root.right = copy(rootRight);
res.add(root);
}
}
}
return res;
}
public TreeNode copy(TreeNode node) {
if (node == null) return null;
TreeNode copyNode = new TreeNode(node.val);
copyNode.left = copy(node.left);
copyNode.right = copy(node.right);
return copyNode;
}
}
可以删除copy(),简化为:
public class Solution {
public List<TreeNode> generateTrees(int n) {
return helper(1, n);
}
public List<TreeNode> helper(int start, int end) {
List<TreeNode> res = new ArrayList<TreeNode>();
if (start > end) {
res.add(null);
return res;
}
for (int i = start; i <= end; i++) {
List<TreeNode> left = helper(start, i-1);
List<TreeNode> right = helper(i+1, end);
for (TreeNode nodeLeft: left) {
for (TreeNode nodeRight: right) {
TreeNode root = new TreeNode(i);
root.left = nodeLeft;
root.right = nodeRight;
res.add(root);
}
}
}
return res;
}
}