96. Unique Binary Search Trees
by Botao Xiao
Question
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:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Thinking:
- Method 1:DP
分析:
- 假设我们有[1,2,3,4,5,6,7,8], 我们可以选取其中任何一个为根节点。
- 当n = 0时,为1;
- 当n = 1时,为1;
- 当n = 2时,数组为[1,2],根节点可以为1,2。dp[2] = dp[0] * dp[1] + dp[1] * dp[0].
- n = 3, dp[3] = dp[0] * dp[2] + dp[1] * dp[2] + dp[2] * dp[0] 每一项分析:左边的可能性个数 * 右边的可能性个数
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= n; i++){
int sum = 0;
for(int j = 0; j < i; j++)
sum += dp[j] * dp[i - 1 - j];
dp[i] = sum;
}
return dp[n];
}
}
二刷
二刷的时候隐约能记得大致的思路,但是还是参考了一刷的结果。
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1; dp[1] = 1;
for(int i = 2; i <= n; i++){
int sum = 0;
for(int j = 0; j < i; j++)
sum += dp[j] * dp[i - 1 - j];
dp[i] = sum;
}
return dp[n];
}
}
Subscribe via RSS