1.题目
给你一个整数 n ,求恰由 n 个节点组成且节点值从 1 到 n 互不相同的二叉搜索树有多少种?返回满足题意的二叉搜索树的种数。
示例 1: 输入:n = 3 输出:5
示例 2: 输入:n = 1 输出:1
提示: 1 <= n <= 19
2.思路
(1)递归 参考LeetCode_二叉搜索树_中等_95.不同的二叉搜索树 II这题中的思想,先构造出所有的满足题意的二叉搜索树,然后再计算它们的种数即可。不过显然这种做法的效率非常低,因为题目只需要计算满足题意的二叉搜索树的种数,中间构造具体的二叉树会消耗大量的时间,所以在LeetCode上测试时会出现运行超时的情况! (2)动态规划_递归
3.代码实现(Java)
class Solution {
public int numTrees(int n) {
return build(1, n).size();
}
public List<TreeNode> build(int low, int high) {
List<TreeNode> res = new ArrayList<>();
if (low > high) {
res.add(null);
return res;
}
for (int i = low; i <= high; i++) {
List<TreeNode> leftTree = build(low, i - 1);
List<TreeNode> rightTree = build(i + 1, high);
for (TreeNode left : leftTree) {
for (TreeNode right : rightTree) {
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
res.add(root);
}
}
}
return res;
}
}
class Solution {
int[][] dp;
public int numTrees(int n) {
dp = new int[n + 1][n + 1];
return calCnt(1, n);
}
public int calCnt(int low, int high) {
if(low > high) {
return 1;
}
if (dp[low][high] != 0) {
return dp[low][high];
}
int res = 0;
for (int mid = low; mid <= high; mid++) {
int leftCnt = calCnt(low, mid - 1);
int rightCnt = calCnt(mid + 1, high);
res += leftCnt * rightCnt;
}
dp[low][high] = res;
return res;
}
}
|