首页 > 程序开发 > 软件开发 > C++ >

LeetCode Unique Binary Search Trees

2013-12-30

Unique Binary Search Trees Given n, how many structurally unique BST& 39;s (binary search trees) that store values 1 n? For example, Given n = 3, there are a total

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

动态规划法


本题关键:如何填表,如何得到计算公式.

需要很仔细画图,一步一步找出规律。

Catlan公式是可以计算这样的题目的,不过Catalan公式也不好理解,还是写个循环解决吧。

class Solution {
public:
	int numTrees(int n)
	{
		vector ta(n+1);
		ta[0] = 1; ta[1] = 1; ta[2] = 2;
		for (int i = 3; i <= n; i++)
		{
			int mid = (i-1)/2;

			for (int j = 0; j < mid; j++)
			{
				ta[i] += ta[j] * ta[i-j-1] *2;
			}

			if (i%2) ta[i] += ta[mid] * ta[mid];
			else ta[i] += ta[mid+1] * ta[mid] * 2;
		}
		return ta[n];
	}
};


相关文章
最新文章
热点推荐