Leetcode之unique-binary-search-trees

原创 2016年05月30日 22:14:06

题目描述:
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.
这里写图片描述

动态规划来解决这道题:
我设bsTreeNum[i]表示共有i个节点时,能产生的BST树的个数
n == 0 时,空树的个数必然为1,因此bsTreeNum[0] = 1
n == 1 时,只有1这个根节点,数量也为1,因此bsTreeNum[1] = 1
n == 2时,
bsTreeNum[2] = bsTreeNum[0] * bsTreeNum[1] +bsTreeNum[1] * bsTreeNum[0]
n == 3时,
bsTreeNum[3] = bsTreeNum[0] * bsTreeNum[2] + bsTreeNum[1] * bsTreeNum[1] +bsTreeNum[2] * bsTreeNum[0]
同时,当根节点元素为 1, 2, 3, 4, 5, …, i, …, n时,基于以下原则的BST树具有唯一性:
以i为根节点时,其左子树构成为[0,…,i-1],其右子树构成为[i+1,…,n]构成
因此,dp[i] = sigma(dp[0…k] * dp[k+1…i]) 0 <= k < i - 1

我们得到了递推关系式,这是解决DP问题的关键!!!!

package suda.alex.leetcode;

import java.util.Scanner;

public class UniqueBSTree {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        System.out.println("input n:");
        int n = scanner.nextInt();
        System.out.println("the number of BST is:" + numTrees(n));
    }
    public static int numTrees(int n) {
        if(n == 0){
            return 1;
        }
        int[] bsTreeNum = new int[n+1];
        bsTreeNum[0] = 1;
        bsTreeNum[1] = 1;
        for(int i=2;i<=n;i++){
            for(int j=0;j<i;j++){
                bsTreeNum[i] += bsTreeNum[j]*bsTreeNum[i-j-1];
            }
        }
        return bsTreeNum[n];

    }

}
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

[leetcode] 96. Unique Binary Search Trees 解题报告

题目链接:https://leetcode.com/problems/unique-binary-search-trees/ Given n, how many structurally uniq...

LeetCode题解——Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. Fo...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

LeetCode(96) Unique Binary Search Trees

题目Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?For exampl...

LeetCode:Unique Binary Search Trees系列

96. Unique Binary Search TreesGiven n, how many structurally unique BST’s (binary search trees) that...

Leetcode 95 Unique Binary Search Trees II

给出n,生成所有存储1-n共n个数的结构上不重复的二叉查找树。

LeetCode Unique Binary Search Trees动态规划方法详解

/************************************************ Given n, how many structurally unique BST’s (bina...

leetcode-动态规划:Unique Binary Search Trees

题目介绍这道题要求可行的二叉查找树的数量解题思路参考http://www.tuicool.com/articles/IFZbAr 其实二叉查找树可以任意取根,只要满足中序遍历有序的要求就可以。从处理...

LeetCode Unique Binary Search Trees 2 递归方法

//递归方法解决 //I start by noting that 1..n is the in-order traversal for any BST with nodes 1 to n. /...

LeetCode笔记:96. Unique Binary Search Trees

1~n的n个数能组成多少个不用的二叉查找树?

Leetcode Unique Binary Search Trees

动态规划,卡特然数
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)