Given an integer n, how many kinds of binary search trees with 1… n as nodes?
Here, map is used to cache the traversal times of each n, which greatly reduces the number of constructions and speeds up time.
class Solution {
Map<Integer,Integer> map = new HashMap();
public int numTrees(int n) {
int sum=0;
if(n<=1){
map.put(n,1);
return 1;
}
if(map.containsKey(n)){
return map.get(n);
}
for(int i=1;i<=n;i++){
sum += numTrees(i-1)*numTrees(n-i);
}
map.put(n,sum);
return sum;
}
}