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]
        
  • 相关阅读:
    委托学习笔记一(调用委托)
    委托和事件— 一个虚构的故事
    WPF中控制窗口状态
    oracle创建DBLINK
    添加路由 route add
    通过脚本执行sql语句
    c#对声音系统的控制
    ProcessBuilder调用外部脚本
    sql server 重新编译所有视图
    silverlight 隐藏ChildWindow 右上角的关闭按钮
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7119991.html
Copyright © 2011-2022 走看看