题目描述
题目难度:Medium
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:
AC代码1
leetcode 上优秀的解法,带解释:
https://leetcode.com/problems/unique-binary-search-trees/discuss/31707/Fantastic-Clean-Java-DP-Solution-with-Detail-Explaination
public int numTrees(int n) {
int [] dp = new int[n+1];
dp[0]= 1;
dp[1] = 1;
for(int level = 2; level <=n; level++)
for(int root = 1; root<=level; root++)
dp[level] += dp[level-root]*dp[root-1];
return dp[n];
}
AC代码2
leetcode 95题的拓展,参考:https://blog.youkuaiyun.com/tkzc_csk/article/details/88567857
class Solution {
public int numTrees(int n) {
if(n < 1) return 0;
return numTrees(1, n);
}
private int numTrees(int left, int right){
if(left > right) return 1;
if(left == right) return 1;
int res = 0;
int leftNum = 0;
int rightNum = 0;
for(int i = left;i <= right;i++){
leftNum = numTrees(left, i - 1);
rightNum = numTrees(i + 1, right);
res += leftNum * rightNum;
}
return res;
}
}