zoukankan      html  css  js  c++  java
  • leetcode之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

    给定一个数n, 计算从1, 到n 有多少种二叉查找树的结构.

    题解:
    看到这个题目,其实是没有想法的,直觉是n 和n-1之间肯定有某种联系。查看了网上的题解后,将自己的理解写下来:

    1. 对于从1到n 个数来说, 每一个数字都可以作为二叉查找树的根节点的。
    2. 当第i个数作为根节点时, 由二叉查找树的性质可以得到:其左边的数都小于i,右边的树都大于i。
      因此i为根节点时,左边的子树的取值范围为:k = 0~i-1, 右边子树的取值范围为 m = i+1 ~n
    3. 当左边子树0~i-1,其种类有d[i-1] 个,右边子树取值为 i+1 ~n 共有n-i-1个 其种类为d[n-i-1]依次为根节点时,
       注意:对于1,2,3 这三个数 和 4,5,6或者是7,8,9构成的子树种类是一样的 由此
    写成表达式为: d[i] = sum(d[k] * d[i-k-1]) 其中k取值为 0~i-1
    举个例子: 比如n=8
    1. 1为根节点时,左边子树的取值为0, 右边的取值范围为: 2~8 共7个数, 因此其种类与d[7] 是一样的 d[8-0-1]
    2. 2为根节点时,左边子树取值为1, 右边的取值为:3~ 8 与d[6] 是一样的, d[8-1-1]
    依次类推:
    初始条件: 当n= 0 时, d[0] = 1
          d[1] = d[0] = 1
          d[2] = d[0]*d[1] + d[1]*d[0]
    采用动态规划来解: 使用n维数组存储d[i]
    for i in range (1, n+1):
      for k in range (0, i):
        d[i] = d[i] + d[k]*d[i-k-1]
    return d[i]
    ~~~~~
  • 相关阅读:
    「UVA12293」 Box Game
    「CF803C」 Maximal GCD
    「CF525D」Arthur and Walls
    「CF442C」 Artem and Array
    LeetCode lcci 16.03 交点
    LeetCode 1305 两棵二叉搜索树中的所有元素
    LeetCode 1040 移动石子直到连续 II
    LeetCode 664 奇怪的打印机
    iOS UIPageViewController系统方法崩溃修复
    LeetCode 334 递增的三元子序列
  • 原文地址:https://www.cnblogs.com/missmzt/p/5525798.html
Copyright © 2011-2022 走看看