zoukankan      html  css  js  c++  java
  • [Leetcode] DP-- 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
    
    Solution:
     

    count the number of ways. use DP.

      (1) Define the subproblem
          dp[i] indicate the number of unique BST rooted at i
     
      (2) Find the recursion (state transition function)
           a. there is 0 node, empty tree
                      dp[0] = 1
                   b. there is 1 node, just root node
                       dp[1] = 1
                  c. there is 2 nodes.   number 1 is rooted,  dp[0]*dp[1];        2 is rooted dp[1]*dp[0]
                       dp[2]  =  dp[0]*dp[1] +  dp[1]*dp[0]
                   d. there is 3 nodes.  number 1 is rooted,  dp[0]*dp[2];        2 is rooted dp[1]*dp[1],   3 is rooted dp[2]*dp[0]
                        dp[3]  =  dp[0]*dp[2]  + dp[1]*dp[1]  + dp[2]*dp[0]
     
              Therefore, the transition function is as follows;
                  dp[k]   = summation(dp[i] * dp[k-1-i])      for i = 0 to k-1
                                                                              and k from 2 to n
            (3) Get the base case
               dp[0] = 1
               dp[1] = 1
     
           
    1  dp = [0] * (n+1)
    2         dp[0] = 1
    3         dp[1] = 1
    4         for k in range(2, n+1):
    5             for i in range(0, k):
    6                 dp[k] += dp[i] * dp[k-1-i]
    7                # print ("dp k: ", dp[k])
    8         
    9         return dp[n]
        
  • 相关阅读:
    python SocketServer
    python Socket网络编程 基础
    Kali 2017 使用SSH进行远程登录 设置 ssh 开机自启动
    用 python 的生成器制作数据传输进度条
    Markdown 语法的简要规则
    初学python之 面向对象
    windows和linux打印树状目录结构
    初学python之生成器
    初学 python 之 模拟sql语句实现对员工表格的增删改查
    使用wifite破解路由器密码
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7119991.html
Copyright © 2011-2022 走看看