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

 

 

Hide Tags
 Tree Dynamic Programming
 
思路:dp
 

如果集合为空,只有一种BST,即空树,

UniqueTrees[0] =1

如果集合仅有一个元素,只有一种BST,即为单个节点UniqueTrees[1] = 1

UniqueTrees[2] = UniqueTrees[0] * UniqueTrees[1]   (1为根的情况)+ UniqueTrees[1] * UniqueTrees[0]  (2为根的情况)。

再看一遍三个元素的数组,可以发现BST的取值方式如下:

UniqueTrees[3] = UniqueTrees[0]*UniqueTrees[2]  (1为根的情况)

+ UniqueTrees[1]*UniqueTrees[1]  (2为根的情况)

+ UniqueTrees[2]*UniqueTrees[0]  (3为根的情况)

所以,由此观察,可以得出UniqueTrees的递推公式为UniqueTrees[i] = ∑ UniqueTrees[0...k] * [i-1-k]     k取值范围 0<= k <=(i-1)

 

class Solution {
    public:
        int numTrees(int n) {

            int *num = new int[n+1];

            num[0] = 1;
            num[1] = 1;
            int tmp = 0;

            for(int i =2; i <=n; i++)
            {   
                tmp = 0;
                for(int j= 0; j <i ;j++)
                    tmp += num[j]*num[i-j-1];
                num[i] = tmp;
            }   

            tmp =  num[n];

            delete []num;

            return tmp;

        }   
};

 

posted @ 2015-04-02 16:02  穆穆兔兔  阅读(156)  评论(0编辑  收藏  举报