1. 程式人生 > >LeetCode96:Unique Binary Search Trees

LeetCode96:Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

Input: 3
Output: 5
Explanation:
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

LeetCode:連結

首先注意這裡是BST而不是普通的Binary Tree,所以數字會對插入的位置有影響。這類找combination/permutation的題都需要找找規律。

n = 0

n = 1

1

n = 2

   1                  2

     \                /

      2            1

n = 3

 1           3    3      2     1

    \        /     /       / \       \

     3    2    1      1   3      2

    /     /        \                    \

   2   1          2                   3

定義f(n)為unique BST的數量,以n = 3為例:

構造的BST的根節點可以取{1, 2, 3}中的任一數字。

如以1為節點,則left subtree只能有0個節點,而right subtree有2, 3兩個節點。所以left/right subtree一共的combination數量為:f(0) * f(2) = 2

以2為節點,則left subtree只能為1,right subtree只能為2:f(1) * f(1) = 1

以3為節點,則left subtree有1, 2兩個節點,right subtree有0個節點:f(2)*f(0) = 2

總結規律:

f(0) = 1

f(n) = f(0)*f(n-1) + f(1)*f(n-2) + ... + f(n-2)*f(1) + f(n-1)*f(0)

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