Leetcode:unique_binary_search_trees

2015-07-20 17:33:00 · 作者: · 浏览: 4

一、 题目

给定数n,问有多少种不同的BST(二叉搜索树)

例如:

由于N =3,共有5种独特的BST。

1 3 3 2 1

\ / / / \ \

3 2 1 1 3 2

/ / \ \

2 1 2 3

二、分析

要求一定的二叉查找树的数量,我们知道二叉查找树可以任意取根。从处理子问题的角度来看,选取一个结点为根,可把结点分成左右子树,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总数量是将以所有结点为根的可行结果累加起来。

看到有人说到卡特兰数,这正是卡特兰数的一种定义方式,是一个典型的动态规划的定义方式。

卡特兰数的一半公式为Cn= 1/(n+1)*(2n,n) = (2n)!/{(n+1)!*n!}



class Solution {
public:
    int numTrees(int n) {
        int flag=1;
        for(int i=2;i<=n;i++) {
        	flag=2*(2*i-1)*flag/(i+1); 
        }
        return flag;
    }
};

二:

 
class Solution {
public:
	int numTrees(int n) 
	{
		return numTrees(1,n);
	}

	int numTrees(int start, int end)
	{
		if (start >= end)
			return 1;

		int totalNum = 0;
		for (int i=start; i<=end; ++i)
			totalNum += numTrees(start,i-1)*numTrees(i+1,end);
		return totalNum;
	}
};




class Solution {
public:
	int numTrees(int n) {
    	if (n < 0) return 0;
           vector
  
    trees(n+1, 0);
        trees[0] = 1;

        for(int i = 1; i <= n; i++) 
            for (int j = 0; j < i; j++) 
                  trees[i] += trees[j] * trees[i-j-1];
        return trees[n];
	}
};