Unique Binary Search Trees

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
采用1维DP来做,以n为分类标准,建造数组,作为存储空间。
注意,对于任意的输入m,m == for all inv in m, number of trees for m += matrix[inv -1] * matrix[m - inv]; [1 , m )
 1 public class Solution {
 2     public int numTrees(int n) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         //[....)
 6         if(n < 1) return 0;
 7         else{
 8             int[] matrix = new int[n + 1];
 9             matrix[0] = 1;
10             matrix[1] = 1;
11             for(int inv = 2; inv < n + 1; inv ++){
12                     int sum = 0;
13                     for(int m = 1; m < inv + 1; m ++){
14                         sum += matrix[m -1] * matrix[inv - m];
15                     }
16                     matrix[inv] = sum;
17             }
18             return matrix[n];
19         }
20     }
21 }

 第二遍: 

 1 public class Solution {
 2     public int numTrees(int n) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         if(n <= 0) return 0;
 6         int[] map = new int[n + 1];
 7         map[0] = 1;
 8         map[1] = 1;
 9         for(int i = 2; i <= n; i ++)
10             for(int j = 1; j <= i; j ++)//root integer
11                 map[i] += map[j - 1] * map[i - j];
12         return map[n];
13     }
14 }

 

posted on 2013-09-26 02:35  Step-BY-Step  阅读(205)  评论(0编辑  收藏  举报

导航