1 题目
2 Java
本题虽然是树的递归,但可以看做动态规划
原因是常规树的递归每个子问题的结果都不一样,无法建立备忘录优化
本题只求个数,[1,2,3]和[2,3,4]两组构成二叉树的数量是一样的,可以建立备忘录优化
2.1 方法一(递归;可看做动态规划)
numi = (num1 * num2)i代表:
i为选定的根节点,0 ~ i-1作为左子树,i+1 ~ n是右子树,且0 ~ i-1构成二叉搜索树数量为num1,i+1 ~ n构成二叉搜索树数量为num2
0 ~ n节点组成的二叉搜索树数量num = num1+num2+num3……nunn
class Solution {
public int numTrees(int n) {
if(n == 0 || n == 1) return 1;
int ans = 0;
for(int i = 1; i <= n; i++){
ans += numTrees(i - 1) * numTrees(n - i);
}
return ans;
}
}
2.2 方法二(优化递归;自顶向下)
带备忘录的递归
class Solution {
public int numTrees(int n) {
int[] memory = new int[n + 1];
return numTrees(n, memory);
}
public int numTrees(int n, int[] memory){
if(n == 0 || n == 1) return 1;
if(memory[n] != 0) return memory[n];
int ans = 0;
for(int i = 1; i <= n; i++){
ans += numTrees(i - 1, memory) * numTrees(n - i, memory);
}
memory[n] = ans;
return ans;
}
}
2.3 方法三(优化迭代;自底向上动态规划)
带备忘录的迭代
class Solution {
public int numTrees(int n) {
int[] memory = new int[n + 1];
memory[0] = 1;
memory[1] = 1;
for(int step = 2; step <= n; step++){
for(int i = 1; i <= step; i++){
memory[step] += memory[i - 1] * memory[step - i];
}
}
return memory[n];
}
}