zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    uva299 Train Swapping
    uva 10106 Product
    uva 340 MasterMind Hints
    uva 10115 Automatic Editing
    uva748 Exponentiation
    uva152 Tree's a Crowd
    uva 10420 List of Conquests
    uva 644 Immediate Decodability
    要知其所以然的学习(转载)
    持有书籍统计
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3339999.html
Copyright © 2011-2022 走看看