`
huntfor
  • 浏览: 196057 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Unique Binary Search Trees

 
阅读更多

新博文地址:[leetcode]Unique Binary Search Trees

http://oj.leetcode.com/problems/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

 刚拿到这道题,直觉是树,但是看了之后发现完全与树关系不大,是个很典型的DP问题:

比如说有1~n,n个节点,我们选择一个中间节点k为根节点,那么左子树就变成了子问题 1 ~ (k-1)有几种构造法,右子树就变成了(k + 1) ~ n有几种构造法,左子树跟右子树的组合数,就是n个节点的构造数;

即f(n) =  sum{ f(k - 1) * f( n - k) | k = 1 ~ n }

容易知道f(0) = f(1) = 1; f(2) = 2;

接下来的编程就容易了:

    public int numTrees(int n) {
        	if(n <= 1){
			return 1;
		}
                int[] num = new int[n + 1];
		num[0] = 1;
		num[1] = 1;
		num[2] = 2;

		for(int i = 3; i <= n; i++){
			for(int j = 1; j <= i; j++){
				num[i] += num[j - 1] * num[i - j];
			}
		}
		return num[n];
    }

虽然AC,但是 时间复杂度略高,不知道有没有O(n)的解法

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics