unique-binary-search-trees

1、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

2、直接看代码:

/**
 * 思路:存在1,2,3...i...n序列;
 * 以第i个元素为根节点的的二叉树数目 = 左子树可以组成的二叉树数目 + 右子树可以组成的二叉排序树数目
 * 下面列出了递归和非递归实现。递归为了避免重复计算“子问题”,也引进了保存数组
 * @author Rail
 *
 */
public class NumTrees {

    public static void main(String[] args){
        NumTrees test = new NumTrees();
        System.out.println(test.numTrees(2));
    }
    int[] arr;
    /**
     * 递归
     * @param n
     * @return
     *//*
    public int numTrees(int n) {
        arr = new int[n];
        arr[0] = 1;
        for(int i = 1; i < n; i++){
            arr[i] = -1;
        }
        int res = reverse(n);
        return res;
    }
    private int reverse(int n) {
        if(n <= 2)
            return n;
        int res = 0;
        for(int i = 0; i < n; i++){
            if(arr[i] == -1)
                arr[i] = reverse(i );
            if(arr[n - 1 - i] == -1)
                arr[n - 1 - i] = reverse(n - 1 - i);
            res += arr[i] * arr[n - 1 - i];
        }
        return res;
    }*/
    //非递归,由下往上
    public int numTrees(int n) {
        if(n == 0)
            return n;
        arr = new int[n + 1];
        arr[0] = 1;

        int i, j;
        for( i = 1; i <= n; i++){
            arr[i] = 0;
            for(j = 0; j < i; j++ ){
                arr[i] += arr[j] * arr[i - 1 - j];
            }
        }


        return arr[n];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值