96. Unique Binary Search Trees

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int numTrees(int n) {
// 二叉搜索树,关键在于枚举 root 节点,确定 root 节点后,小于 root 节点值的在左边,大于 root 节点值的在右边

int[] dp = new int[n + 1];
dp[0] = dp[1] = 1;

for (int i = 2; i < dp.length; i++) {
for (int root = 1; root <= i; root++) {
dp[i] += dp[root - 1] * dp[i - root]; // cartesian product
}
}

return dp[n];
}
}

References

96. Unique Binary Search Trees