Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
动态规划。
dp[i]表示n = i时的结果,dp[i]的生成:
从0遍历到i,对每个数字的左边的可能数,乘以右边的可能数。再每个相加。
class Solution {
public int numTrees(int n) {
if (n <= 2) {
return n;
}
int[] dp = new int[n + 1];
// 如果子树没有元素,那么就只有一种可能,就是null
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
// 左边的子树的可能数 * 右边子树的可能数
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
}
本文探讨了如何计算给定数值范围内的独特二叉搜索树的数量,采用动态规划算法解决LeetCode上的一道经典问题。通过递增计算,利用子问题的解来构建更复杂问题的解,实现了高效求解。

被折叠的 条评论
为什么被折叠?



