树——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
方法:
当给定n后,从1-n的数都可以作为头结点,当i(1=<i<=n)作为头结点时,其左子树结点个数可以有j(0=<j<i)个,相应的右子树结点个数有
i-1-j(总结点个数为i,头结点1个,左子树j个)个,则原问题可化为子问题求解。
递推公式为:
                      1;                 {n == 0||n == 1}
numTrees(n)=   
              for(int i=1;i<=n;i++)      {n>=2}       
               {<span style="line-height: 22.4px; font-family: Courier, 'Courier New', monospace; white-space: pre-wrap;">//1-n都可以作为头结点
</span>                for(int j=0;j<i;j++)
                 {
                  numTrees(j)*numTrees(n-j-1);
                 }
               }
直接用递归求解会超时,所以用动态规划求解。
代码如下
public int numTrees(int n) {     
            if(n<0)
            return 0;
        
        int []count=new int[n+1];
        count[0]=1;
        count[1]=1;
        for(int i=2;i<=n;i++)  //计算n==2 到n==n的情况;
             {
              for(int j=0;j<i;j++)
               {
                 count[i]+=count[j]*count[i-j-1];
               }
             }
        return count[n];
    }




 

你可能感兴趣的:(树——unique-binary-search-trees)