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.spa

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

 

  Tree Dynamic Programming
 
 
若是集合爲空,只有一種BST,即空樹,
UniqueTrees[0] =1

若是集合僅有一個元素,只有一種BST,即爲單個節點
UniqueTrees[1] = 1
 

UniqueTrees[2] = UniqueTrees[0] * UniqueTrees[1]   (1爲根的狀況)
                  + UniqueTrees[1] * UniqueTrees[0]  (2爲根的狀況。

再看一遍三個元素的數組,能夠發現BST的取值方式以下:
UniqueTrees[3] = UniqueTrees[0]*UniqueTrees[2]  (1爲根的狀況)
               + UniqueTrees[1]*UniqueTrees[1]  (2爲根的狀況)
               + UniqueTrees[2]*UniqueTrees[0]  (3爲根的狀況)

因此,由此觀察,能夠得出UniqueTrees的遞推公式爲
UniqueTrees[i] = ∑ UniqueTrees[0...k] * [i-1-k]     k取值範圍 0<= k <=(i-1)code

 

 
'''
Created on Nov 13, 2014
 
@author:  ScottGu<gu.kai.66@gmail.com, kai.gu@live.com>
'''
class   Solution  :
     # @return an integer
     def  numTrees(  self  , n):
        uniqueTrees={}
        uniqueTrees[  0  ]= 1
        uniqueTrees[  1  ]= 1
 
         for  cnt  in  range(  2 , n+  1  ):
            uniqueTrees[cnt]=  0
             for  k  in  range(  0 , cnt):
                uniqueTrees[cnt]+=uniqueTrees[k]*uniqueTrees[cnt-  1  -k]
 
         return  uniqueTrees[n]
       
       
if  __name__ ==  '__main__'  :
    sl=Solution()
     print  sl.numTrees(  0  ),  0
     print  sl.numTrees(  1  ),  1
     print  sl.numTrees(  2  ),  2
     print  sl.numTrees(  3  ),  3
     print  sl.numTrees(  4  ),  4
     print  sl.numTrees(  5  ),  5
相關文章
相關標籤/搜索