96. Unique Binary Search Trees
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
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
解法
动态规划,1-n,选择任意一个数作为根结点
状态值:G[n]表示,当n = n时,二叉搜索树的个数。
初始化:G[0] = 1, G[1] = 1,表示 n=0 和 n=1 时二叉搜索树的个数。
转移方程:G[n] = G[0] * G[n - 1] + G[1] * G[n - 2] + … + G[n - 1] * G[0]。
public class Solution {
public int numTrees(int n) {
if (n == 0) {
return 0;
}
int[] state = new int[n + 1];
state[0] = 1;
state[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
state[i] += state[j - 1] * state[i - j];
}
}
return state[n];
}
}