Given an interger N, how many structurally unique binary search trees are there that store values 1...N?
For example, for N = 2, there are 2 unique BSTs
1 2
/
2 1
1 2
/
2 1
For N = 3, there are 5 possible BSTs
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Input:
First line contains the test cases T. 1<=T<=15
Each test case have one line which is an interger N. 1<=N<=11
Example:
Input:
2
2
3
Output:
2
5
leetcode原题。
注意下dp数组的初始条件
dp[0] = 1; 找子问题的时候 dp[0] = 1表示某一边没有孩子,1 * 对应另边的情况。
代码:
public static void main (String[] args)
{
//code
Scanner input = new Scanner(System.in);
int number = input.nextInt();
int[] inputArray = new int[number];
int[] result = new int[number];
for(int i=0;i<number;i++){
inputArray[i] = input.nextInt();
result[i] = compute(inputArray[i]);
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
}
private static int compute(int number){
if(number == 0) return 1;
if(number == 1) return 1;
if(number == 2) return 2;
int[] dp = new int[number+1];
//Arrays.fill(dp, 0);
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
for(int i=3;i<=number;i++){
for(int k=1;k<=i;k++){
dp[i] += dp[k-1] * dp[i-k];
}
}
return dp[number];
}