【LeetCode】#96不同的二叉搜索树(Unique Binary Search Trees)
题目描述
给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \
3 2 1 1 3 2
/ / \
2 1 2 3
Description
Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
Example
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST’s:
1 3 3 2 1
\ / / / \
3 2 1 1 3 2
/ / \
2 1 2 3
解法
解法1:
class Solution {
public int numTrees(int n) {
if(n == 0) return 0;
HashMap<Integer,Integer> hm = new HashMap<>();
hm.put(1,1);
int start = 2;
while(start <= n){
int val = 2 * hm.get(start - 1);
int newEnd = start,newStart = 1;
newEnd -= 2;
while(newStart <= newEnd){
if(newStart < newEnd){
val += hm.get(newStart) * hm.get(newEnd) * 2;
}else{
val += hm.get(newStart) * hm.get(newEnd);
break;
}
newStart++;
newEnd--;
}
hm.put(start,val);
start++;
}
return hm.get(n);
}
}
解法2:
class Solution {
public int numTrees(int n) {
int nums[] = new int[n+1];
nums[0] = 1;
nums[1] = 1;
for(int i=2; i<=n; i++){
for(int j=0; j<i; j++){
nums[i] = nums[j] * nums[i-j-1] + nums[i];
}
}
return nums[n];
}
}