• 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 }
  • 相关阅读:
    可扩展设计的三个维度
    今天用批处理脚本遇到的两个问题
    响应式编程学习记录
    ThreadLocal使用注意
    JDK8 函数式接口
    Java多线程相关的常用接口
    java异步编程
    java多线程同步器
    paramiko获取远程主机的环境变量
    python为不同的对象如何分配内存的小知识
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3339999.html
Copyright © 2020-2023  润新知