Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
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
直接想到遞歸,給定i作爲根,左右子樹還有i-1,n-i個值,遞歸進行計算,累加起來得到結果:
public class Solution {
public static int count(int n,int i){
if(i==1||i==0)return 1;
return count(i-1)+count(n-i);
}
public int numTrees(int n) {
int i;
int res=0;
for(i=1;i<=n;i++)res+=count(n,i);
return res;
}
}