leetCode(26):Unique Binary Search Trees 分类: leetCode 2015-06-23 14:09 155人阅读 评论(0) 收藏

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
1)结构的总数和存储的n个有序数没有关系,即存放的是1,2,3或5、6、9结果都是一样的;
2)n=01时,结果都为1;n个有序数,取任何一个作为根结点,该值左边的为左子树,右边的为右子树,
在这种情况下,可能的结构总数为:左子树结构数*右子树结构数,所以原问题就被分解成了两个子问题;
3)将取n个有序数作为根结点的情况的结构问题相加,即可得到原问题的解,但应注意的是,如:1、2、3
取1或3作为根结点的情况,结构数是相同的,即具有对称性;那么也要考虑到奇偶性;
4)能够被分解成相同的子问题,自己就可以采用递归,本程序采用循环的方法。
*/ 
int numTrees(int n)
{
	vector<int> store;
	store.push_back(1);
	store.push_back(1);
	for(int i=2;i<=n;++i)
	{		
		int tmp=0;
		for(int j=0;j<i/2;++j)
		{
			tmp+=2*store[i-1-j]*store[j];
		}
		if(i%2)
			tmp+=store[i/2]*store[i/2];
				
		store.push_back(tmp);		
	}
	return store[n];
}




原文地址:https://www.cnblogs.com/zclzqbx/p/4687089.html