[LeetCode] 96. Unique Binary Search Trees Java

题目:

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
题意及分析:
给出一个整数n,用1到n的数构成一棵二叉搜索树,问有几种方式。这道题我是没有思路了,查找了网上的解题思路基本上都是一致的,即用动态规划的方法。因为对于二叉搜索树有:
选取一个点作为根节点,然后将这棵树分成左右子树,那么以这个点作为根节点的二叉树的方法为左右二叉树可行方法的乘积,对每种可能的根节点求可行方法,然后累加起来即可得到值。以n=3时为列,维护一个一维数组作为i为根节点的方法,因为二叉搜索树中序遍历是有序的,所以:
(1)1为根节点时,左子树0个节点,右子树2个节点,有A[0]*A[2]种方法;
(2)2为根节点时,左子树1个节点,右子树1个节点,有A[1]*A[1]种方法;
(3)3为根节点时,左子树2个节点,右子树0个节点,有A[2]*A[0]种方法;
故A[3]=
A[0]*A[2]+A[1]*A[1]+A[2]+A[0]


代码:
public class Solution {

	public int numTrees(int n) {		//二叉搜索树 按照中根序遍历肯定是递增的
		 if(n ==0 || n ==1) return 1;
        int[] A=new int[n+1];
        A[0] =1;
        for(int i=1;i<=n;i++){
        	for(int j=0;j<i;j++)
        		A[i] += A[j]*A[i-j-1];
        	
        }
        	return A[n];
    }
}

  

 



 
原文地址:https://www.cnblogs.com/271934Liao/p/6917489.html