Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
The idea is Suppose we know the solution from 1 to n-1, and we want to know about n;
F(n) = 0;
We could choose a number X from 1 to n to be the root, and all the numbers in the left subtree i < X and in the right tree i > X
There are (i - 1) number in the left tree and (n - i) number in the right tree.
F(n) += F(i - 1) * F(n - i) for i from 1 to N
Code:
public class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
dp[0] = 1;
if(n <= 1) return 1;
for(int i = 2; i <= n; i++){
for(int k = 0; k < i; k++){
dp[i] += dp[k]*dp[i-k-1];
}
}
return dp[n];
}
}in the above code k stands for how many number in the left tree and (i - k - 1) stands for how many number in the right tree.
本文介绍了一种生成所有结构上唯一的二叉搜索树(BST)的算法,这些BST存储从1到n的值。通过递归地选择根节点并确定左右子树的元素数量来解决该问题。给出的代码实现了这一算法,并展示了当n为3时,可以生成5棵不同的二叉搜索树。
449

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



