您的位置:首页 > 产品设计 > UI/UE

*[Lintcode]Unique Binary Search Trees 不同的二叉查找树

2016-11-17 16:42 459 查看
Given n,
how many structurally unique BSTs
(binary search trees) that store values 1...n?

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


分析:递归法。n=19时超时.

public class Solution {
/**
* @paramn n: An integer
* @return: An integer
*/
public int numTrees(int n) {
if(n == 0 || n == 1) return 1;
return helper(n, 1, n);
}

int helper(int n, int start, int end) {
if(start == end) return 1;
int res = 0;
for(int i = start; i <= end; i++) {
int left = 1, right = 1;
if(i > start) left = helper(n, start, i - 1);
if(i < end) right = helper(n, i + 1, end);
res += left * right;
}
return res;
}
}

网上看了一下,可以使用一维动态规划。res[i]代表n=i时,不同排列数量。res[i] = res[0]*res[i-1] + res[1]*res[n-2] ......
其中res[0]*res[n-1]代表i做root时,左边0个点,右边n-1个点时的排列数。在考虑解法时,要忽略掉数字。

public class Solution {
/**
* @paramn n: An integer
* @return: An integer
*/
public int numTrees(int n) {
if(n == 0 || n == 1) return 1;
int[] res = new int[n + 1];
res[0] = 1;

for(int i = 1; i <= n; i++) {
for(int j = 0; j < i; j++) {
res[i] += res[j] * res[i - 1 - j];
}
}
return res
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode