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
[code]
public class Solution {
int dp[];
public int numTrees(int n) {
if(n<=0)return 0;
if(n==1)return 1;
dp=new int [n+1];
helper(n);
return dp[n];
}
int helper(int n)
{
if(n<=1)return 1;
int sum=0;
for(int i=0;i<n;i++)
{
int j=n-i-1;
dp[i]= dp[i]==0 ? helper(i) : dp[i];
dp[j]= dp[j] ==0 ? helper(j) : dp[j];
sum+=dp[i]*dp[j];
}
dp[n]=sum;
return dp[n];
}
}
[Thoughts]
注意dp[0]=1, not 0.
Given n, generate all structurally unique BST’s (binary search trees) that store values 1…n.
[code]
public class Solution {
int array[];
public List<TreeNode> generateTrees(int n) {
if(n<=0)
{
List<TreeNode> list=new ArrayList<TreeNode>();
list.add(null);
return list;
}
array=new int[n];
for(int i=0;i<n;i++)array[i]=i+1;
return helper(0, n-1);
}
List<TreeNode> helper(int low, int high)
{
List<TreeNode> trees=new ArrayList<TreeNode>();
if(low>high)
{
trees.add(null);
return trees;
}
int n=high-low+1;
for(int i=low-1;i<=high-1;i++)
{
List<TreeNode> left=helper(low, i), right=helper(i+2, high);
for(TreeNode e1: left)
{
for(TreeNode e2: right)
{
TreeNode root=new TreeNode(array[i+1]);
root.left=e1;root.right=e2;
trees.add(root);
}
}
}
return trees;
}
}
[Thoughts]
依然是0的时候容易出错,返回的不是空list,应该包含一个null.