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

【leetcode】 Unique Binary Search Trees

2015-06-23 22:51 776 查看
From : https://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

任选一个结点作为根结点,那么这棵树的组合为其左边树的组合数目乘以右边的组合数目,即
num[i] =
Σ num[k-1]*num[i-k] (1<=k<=i)

那么从小到大求可以依次求出num[i[, 最后返回num
即可。

class Solution {
public:
int numTrees(int n) {
if(n < 1) return 0;
if(n < 3) return n;
vector<int> num(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
;
}
};
public class Solution {
public int numTrees(int n) {
if (n < 1) {
return 0;
}
if (n < 3) {
return n;
}
int[] num = new int[n + 1];
num[0] = 1;
num[1] = 1;
num[2] = 2;
for (int i = 3; i <= n; i++) {
// length = i
for (int j = 1; j <= i; j++) {
// root is j
num[i] += num[j - 1] * num[i - j];
}
}
return num
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: