[LeetCode]: 96: 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

 

分析:

这个题需要采用动态规划的思想,即:最终解只有部分解逐一累加完成的。基于这个思路再看看本题的分析

当节点数为0的时候,返回0个解

当节点数为1的时候,返回1个解

当节点数为2的时候,返回2个解

当节点数为3的时候,返回5个解,如上图。包括1为顶点的两种解,2为顶点的1种解和3为顶点的2种解。

当节点数为4的时候,返回15个解,包括当1为顶点的5中解,2为顶点的2种解,3为顶点的2种解和4为顶点的5种解。

由此可见关于平衡二叉树子树的情况:

    - 某一个点为顶点的时候,子树的个数为:左子树的个数乘以右子树的个数。

    - 多个点的构成的平衡二叉树的个数应该为:其中每一个点作为顶点时其子树的个数 的和。

 

本题目最简便的方法是节点数从小到大依次计算,节点多的时候,将节点划分成几个小的节点组合,采用之前计算的结果

 

代码如下:

    public static int numTrees(int n) {
        switch(n){
            case 0:
                return 0; 
            case 1:
                return 1;
            case 2:
                return 2;
            default:
                int[] arrResult = new int[n+1];
                arrResult[0] = 1;  // 零个节点时候,子树应该为零,但是为了后面左右子树相乘的计算方便,在此强置为1
                arrResult[1] = 1;
                arrResult[2] = 2;
                
                for(int i = 3;i<=n;i++){  //3个节点开始采用动态规划的方法
                    int intResultTemp = 0;
                    for(int j = 0 ; j<i;j++ ){
                        intResultTemp = intResultTemp + (arrResult[j]*arrResult[i-j-1]);   //左子树数目乘以右子树数目
                    }
                    arrResult[i] = intResultTemp;
                }
                return arrResult[n];          
         }
    }

 

 

 

posted @ 2015-10-07 17:54  savageclc26  阅读(152)  评论(0编辑  收藏  举报