96. Different binary search trees
Problem-solving ideas
- base case dp[0] = 1 An empty node is also a binary tree
- Status: dp[i] For each node i as the root node, how many binary search trees are there?
- Outer loop: Traverse all possible node numbers. Memory loop traverses all left and right subtree combinations.
class Solution {
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
dp[i] += dp[i - j] * dp[j - 1];
}
}
return dp[n];
}
}