1. Title
Unique Binary Search Trees
2. Http address
https://leetcode.com/problems/unique-binary-search-trees/
3. The question
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
4 My code (AC)
1 public class UniqueBinarySearchTrees { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 System.out.println(numTrees(50)); 6 } 7 8 // Accepted 9 public static int numTrees(int n) { 10 11 if ( n == 0) 12 return 0; 13 if ( n == 1) 14 return 1; 15 if ( n == 2) 16 return 2; 17 if ( n == 3) 18 return 5; 19 int sum; 20 int opt[] = new int[n+1]; 21 opt[1] = 1; 22 opt[2] = 2; // n == 2; 23 opt[3] = 5; // n == 3; 24 for( int i = 4; i <= n; i++) 25 { 26 // sum = [opt(1) * opt(n-2) + opt(3) * opt ( n-3) ..... + opt(n-1) * opt(1)] n = i -2; 27 sum = 0; 28 for( int j = 1; j <= i - 2; j++) 29 { 30 sum += opt[j] * opt[i-j-1]; 31 } 32 opt[i] = 2 * opt[i-1] + sum; 33 } 34 return opt[n]; 35 } 36 37 }