力扣labuladong一刷day36天
一、96. 不同的二叉搜索树
题目链接:https://leetcode.cn/problems/unique-binary-search-trees/
思路:这是一道典型的动态规划题,从n=3来看 子树有几种形态 (0, 2)、(1, 1)、(2, 0)有规律可循,即为左子树为0的种数*右子树为2的种数 + 左子树为1的种树 * 右子树为1的种树 + 左子树为2的种数 * 右子树为0的种数。定义dp数组表示dp[i]为n=i时二叉搜索树的种数,递推公式dp[i]=dp[j]*dp[i-j-1] (i<=n, j < i),初始化dp[0]=1, dp[1]=1, dp[2]=2;
class Solution {public int numTrees(int n) {if (n == 1) return 1;int[] dp = new int[n+1];dp[0] = 1;dp[1] = 1;dp[2] = 2;for (int i = 3; i <= n; i++) {for (int j = 0; j < i; j++) {dp[i] += dp[j] * dp[i - j -1];}}return dp[n];}
}
二、95. 不同的二叉搜索树 II
题目链接:https://leetcode.cn/problems/unique-binary-search-trees-ii/
思路:
class Solution {public List<TreeNode> generateTrees(int n) {if (n == 0) return new ArrayList<>();return build(1, n);}List<TreeNode> build(int lo, int hi) {List<TreeNode> res = new LinkedList<>();// base caseif (lo > hi) {res.add(null);return res;}// 1、穷举 root 节点的所有可能。for (int i = lo; i <= hi; i++) {// 2、递归构造出左右子树的所有有效 BST。List<TreeNode> leftTree = build(lo, i - 1);List<TreeNode> rightTree = build(i + 1, hi);// 3、给 root 节点穷举所有左右子树的组合。for (TreeNode left : leftTree) {for (TreeNode right : rightTree) {// i 作为根节点 root 的值TreeNode root = new TreeNode(i);root.left = left;root.right = right;res.add(root);}}}return res;}
}