• leetcode96 Unique Binary Search Trees


     1 """
     2 Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
     3 Example:
     4 Input: 3
     5 Output: 5
     6 Explanation:
     7 Given n = 3, there are a total of 5 unique BST's:
     8 
     9    1         3     3      2      1
    10            /     /      /       
    11      3     2     1      1   3      2
    12     /     /                        
    13    2     1         2                 3
    14 """
    15 """
    16 数学分析,让每个值作为根结点,再讨论
    17 左右子树结点的数量,能得到
    18 res[1]=1
    19 res[2]=res[1]*res[0]+res[0]*res[1]
    20 res[3]=(res[0]*res[2])+(res[1]*res[1])+(res[2]*res[0])
    21 令res[0]=1保证树的一边为空存在
    22 """
    23 class Solution:
    24     def numTrees(self, n):
    25         res = [0]*(n+1)
    26         res[0], res[1] = 1, 1
    27         for i in range(2, n+1):
    28             for j in range(i):
    29                 res[i] += res[j]*res[i-j-1]
    30         return res[n]
  • 相关阅读:
    文字
    <script type="text/x-template"> 模板
    防xss攻击
    url
    symmfony
    composer
    header 和http状态码
    bootstrap
    linux的设置ip连接crt,修改主机名,映射,建文件
    Centos上传下载小工具lrzsz
  • 原文地址:https://www.cnblogs.com/yawenw/p/12416547.html
Copyright © 2020-2023  润新知