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
以n为根结点的二叉树个数=左子树个数*右子树个数
用数组recordn+1记录以0~n的情况,自底向上,否则会超时
public int numTrees(int n) {
if (n == 1 || n == 2) {
return n;
}
// record[0]没有用,所以长度是n+1
// 使用数组,从下向上保存结果,能够节省时间,否则会超时
int[] record = new int[n + 1];
record[0] = 1;
record[1] = 1; // 1个元素时,情况为1
record[2] = 2; // 2个元素时,情况为2
for (int i = 3; i <= n; i++) {
int tmp = 0;
for (int k = 0; k < i; k++) {
// 以n为根结点的二叉树个数=左结点的二叉树个数*右结点的二叉树个数
// 题目所求要包括所有情况,分别以1~n为根结点
tmp += (record[k] * record[i - k - 1]);
}
// 记录1~i时,BST的个数
record[i] = tmp;
}
return record[n];
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有