LeetCode 96 Unique Binary Search Tree(Python详解及实现)

【题目】

Given an integer n, generate allstructurally unique BST's (binary search trees) that store values 1...n.

 

For example,

Given n = 3, your program should return all5 unique BST's shown below.

 

  1         3     3     2      1

   \       /     /     / \      \

    3     2     1     1   3      2

   /     /       \                 \

  2     1         2                 3

这道题与94题类似,94题求得是符合条件的二叉树的棵树,这题是返回所有符合条件的二叉查找树。

【思路】

动态规划求解:

         问题的状态转移方程怎么求呢?大部分动态规划的难点都是求状态转移方程。

n=0时,为空树,----> dp[0]=1;

n=1时, dp[1]=1;

n=2时,dp[2]=2;

n>2时,dp[n]=dp[0]*dp[n-1]+dp[1]*dp[n-2]+......+dp[n-1]*dp[0];

【Python实现】

#动态规划迭代求解

class Solution(object):
   def numTrees(self, n):
       """
       :type n: int
       :rtype: int
       """
       dp = [1, 1, 2]
       if n < 3: return dp[n]
       dp += [0 for i in range(n-2)]
       for i in range(3, n+1):
           for j in range(i):
                dp[i] += dp[j]*dp[i-j-1]
       return dp[n]
if __name__ == '__main__':
    S= Solution()
   res = S.numTrees(3)
   print(res)   
   

#递归求解   

class Solution(object):
   def numTrees(self, n):
       """
       :type n: int
       :rtype: int
       """
       dp = [1, 1, 2]
       if n < 3: return dp[n]
       ans = 0 
       for i in range(n): 
           ans += self.numTrees(i)*self.numTrees(n-i-1) 
       return ans
 
 
if __name__ == '__main__':
    S= Solution()
   res = S.numTrees(3)
   print(res)   


 

 

 

  

 

你可能感兴趣的:(LeetCode 96 Unique Binary Search Tree(Python详解及实现))