不同的二叉搜索樹
題目描述
給定一個整數 n,求以 1 … n 爲節點組成的二叉搜索樹有多少種?
示例:
輸入: 3
輸出: 5
解釋:
給定 n = 3, 一共有 5 種不同結構的二叉搜索樹:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
解題思路
個人AC
DFS + 哈希表剪枝
- f(0) = 1;
- f(1) = 1;
- f(2) = 2f(0)f(1);
注:根節點爲1,左子樹元素個數爲0,右子樹元素爲1;根節點爲2,左子樹元素個數爲1,右子樹元素個數爲0
; - f(3) = 2f(0)f(2) + f(1)f(1);
- f(4) = 2f(0)f(3) + 2f(1)f(2);
- f(5) = 2f(0)f(4) + 2f(1)f(3) + f(2)f(2);
- …
class Solution {
private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>() {
{
this.put(0, 1);
this.put(1, 1);
}
};
private int c = 0;
public int numTrees(int n) {
int sum = 0;
if (n == 0 || n == 1) return map.get(n);
for (int i = 0, j = n - 1; i <= j; i++, j--) {
if (i == j) {
int a;
if (map.containsKey(i)) a = map.get(i);
else a = numTrees(i);
sum += a * a;
} else {
int a, b;
if (map.containsKey(i)) a = map.get(i);
else a = numTrees(i);
if (map.containsKey(j)) b = map.get(j);
else b = numTrees(j);
sum += (a * b) << 1;
}
}
map.put(n, sum);
return sum;
}
}
時間複雜度: ;
空間複雜度: 。
動態規劃
class Solution {
public int numTrees(int n) {
int[] memo = new int[n + 1];
memo[0] = 1;
memo[1] = 1;
for (int i = 2; i <= n; i++) {
int sum = 0;
for (int l = 0, r = i - 1; l <= r; l++, r--) {
if (l == r) {
sum += memo[l] * memo[l];
} else {
sum += (memo[l] * memo[r]) << 1;
}
}
memo[i] = sum;
}
return memo[n];
}
}
時間複雜度: ;
空間複雜度: 。
最優解
同上。