LeetCode96_Unique Binary Search Trees(求1到n这些节点能够组成多少种不同的二叉查找树) 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
解题:

用递归的思想,当仅仅有0个或是1个节点的时候。仅仅有一种。n个节点的时候有f(n)种:

左边能够有n-1个节点,右边0个节点,依据对称性能够左右互换。这时候有2*f(n-1)*f(0);

一边1个,还有一边n-2个,这时候有2*f(1)*f(n-2);

一边两个,一边N-3个,这时候有2*f(2)*f(n-3);

。。。

。。。

假设n为奇数,两边都是n/2个。这时候有f(n/2)*f(n/2),假设n为偶数,一边n/2一边(n/2+1)个,为2*f(n/2)*f(n/2+1);


代码:

  public static int numTrees(int n) {
    	 if(n==1||n==0)
    		 return 1;
    	 int sum=0;
    	 if(n%2==0)
    	 {
    		 for(int k=n-1;k>=n/2;k--)
        	 {
        		 sum+=2*numTrees(k)*numTrees(n-1-k);
        	 }
        	 return sum;
    	 
    	 }
    	 else {
    		 for(int k=n-1;k>n/2;k--)
        	 {
        		 sum+=2*numTrees(k)*numTrees(n-1-k);
        	 }
        	 return sum+numTrees(n/2)*numTrees(n/2);
		}
        
    }




原文地址:https://www.cnblogs.com/wzjhoutai/p/6936267.html