LeetCode六月挑战(6.24 )Unique Binary Search Trees LeetCode 96解题方案
题目描述
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
思路
代码
class Solution {
public int numTrees(int n) {
if(n<1)
return 0;
int[][] dp=new int[n+1][n+1];
return f(1,n,dp);
}
public int f(int i,int j,int[][] dp){
if(i==j || i>j) return 1;
if(dp[i][j]!=0) return dp[i][j];
int sum=0;
for(int x=i;x<=j;x++){
sum+=f(i,x-1,dp)*f(x+1,j,dp);
}
dp[i][j]=sum;
return dp[i][j];
}
}