zoukankan      html  css  js  c++  java
  • 【LeetCode】96.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
    
    Hide Tags
     Tree Dynamic Programming
     

    新建一个数组为UniqueTrees[n],对应数组元素为i个节点对应的二叉查找树的数目。取一个数为根节点,比其小的数有p个,比其大的数有q个,则以此为根节点的数对应的二叉查找树有p*q个

    UniqueTrees[0]=1;UniqueTrees[1]=1;UniqueTrees[2]=UniqueTrees[0]*UniqueTrees[1]+UniqueTrees[1]*UniqueTrees[0];

    观察可得递推公式为UniqueTrees[i] = ∑ UniqueTrees[0...k] * [i-1-k]     k取值范围 0<= k <=(i-1)

     
     1 class Solution {
     2 public:
     3     int numTrees(int n) {
     4         if (0 == n || 1 == n)
     5             return 1;
     6         if (2 == n)
     7             return 2;
     8         // 此时n>=3,可以递归的
     9         int UniqueTrees[n] ={1,1,2};
    10         for (int i = 3; i <= n; i++)
    11         {
    12             UniqueTrees[i] = 0;
    13             for (int j = 0; j < i; j++)
    14             {
    15                 UniqueTrees[i] += UniqueTrees[j] * UniqueTrees[i-1-j];
    16             }
    17         }
    18         return UniqueTrees[n];
    19     }
    20 };
    19 / 19 test cases passed.
    Status: 

    Accepted

    Runtime: 1 ms
    Submitted: 0 minutes ago

    WA过一次,当时未加UniqueTrees[i] = 0;关于数组的初始化补充于其下:

    1、首先数组初始化的维度必须是一个常数,这个经常会遇到,比如int cnt = 2; int bad[cnt];这是会报错的。如果是const int cnt = 2;就不会。

    2、对于的数组的初始化,如果没有显式提供元素初值,则数组元素会像普通变量一样初始化:

    1. 在函数体外定义的内置数组,其元素均初始化为 0;
    2. 在函数体内定义的内置数组,其元素无初始化;
    3. 不管数组在哪里定义,如果其元素为类类型,则自动调用该类的默认构造函数进行初始化;
    4. 如果该类没有默认构造函数,则必须为该数组的元素提供显式初始化。

    3、显示初始化,即可以对数组元素进行列表初始化,此时允许忽略数组的维度,编译器会计算并推测。如果维度比提供的初始值数量大,则用提供的的初始值初始化考前的元素,剩下的元素被初始化成默认值。

    e.g int a[5] = {1,2}; // 等价为a[5]={1,2,0,0,0};

    我原本就是这样想的,所以就没有加UniqueTrees[i] = 0;这里的问题是默认初始化即无初始化,所以要多多注意这个初始化这个问题,多写一句。

  • 相关阅读:
    [Daily Coding Problem 223] O(1) space in order traversal of a binary tree
    [Daily Coding Problem 224] Find smallest positive integer that is not the sum of a subset of a sorted array
    Sliding Window Algorithm Questions
    Sweep Line Algorithm Summary
    Palindrome Algorithm Questions
    Core Data Structures, Algorithms and Concepts
    [LeetCode] 1000. Minimum Cost to Merge Stones
    UVA 253 Cube painting(枚举 模拟)
    Codeforces 821C Okabe and Boxes
    Codeforce 741B Arpa's weak amphitheater and Mehrdad's valuable Hoses(并查集&分组背包)
  • 原文地址:https://www.cnblogs.com/helloWaston/p/4483047.html
Copyright © 2011-2022 走看看