Leetcode Unique binary search trees I, II

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值