Unique BST's

Given an interger N, how many structurally unique binary search trees are there that store values 1...N?

For example, for N = 2, there are 2 unique BSTs
     1               2  
                  /
       2         1
For N = 3, there are 5 possible BSTs
  1              3        3         2      1
    \           /        /           /    \      \
     3        2         1        1    3      2
    /       /                \                      \
   2      1               2                        3


Input:
First line contains the test cases T.  1<=T<=15
Each test case have one line which is an interger N.  1<=N<=11

Example:
Input:
2
2
3

Output:
2
5

leetcode原题。

注意下dp数组的初始条件

dp[0] = 1; 找子问题的时候 dp[0] = 1表示某一边没有孩子,1 * 对应另边的情况。

代码:

	public static void main (String[] args)
    {
        //code
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        int[] inputArray = new int[number];
        int[] result = new int[number];
        for(int i=0;i<number;i++){
            inputArray[i] = input.nextInt();
            result[i] = compute(inputArray[i]);
        }
        for(int i=0;i<result.length;i++){
            System.out.println(result[i]);
        }
    }

    private static int compute(int number){
        if(number == 0) return 1;
        if(number == 1) return 1;
        if(number == 2) return 2;

        int[] dp = new int[number+1];
        //Arrays.fill(dp, 0);
        dp[0] = 1;
        dp[1] = 1;
        dp[2] = 2;
        for(int i=3;i<=number;i++){
            for(int k=1;k<=i;k++){
                    dp[i] += dp[k-1] * dp[i-k];
            }
        }
        return dp[number];
    }





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值