leetcode: 96. Unique Binary Search Trees

来源:互联网 发布:json 中括号 编辑:程序博客网 时间:2024/06/14 10:17

Q

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

AC

class Solution(object):    def numTrees(self, n):        """        :type n: int        :rtype: int        """        if n==0:return 1        if n==1:return 1        if n==2:return 2        if n==3:return 5        self.map = {0:1, 1:1, 2:2, 3:5}        return self._getnum(n)    def _getnum(self, n):        if n in self.map:            return self.map[n]        total = 0        for i in range(n):            left = self._getnum(i)            right = self._getnum(n-i-1)            total += left*right        self.map[n] = total        return total# Time:  O(n)# Space: O(1)# Math solution.class Solution2(object):    def numTrees(self, n):        """        :type n: int        :rtype: int        """        if n == 0:            return 1        def combination(n, k):            count = 1            for i in xrange(1, k + 1):                count = count * (n - i + 1) / i;            return count        return combination(2 * n, n) - combination(2 * n, n - 1)# Time:  O(n^2)# Space: O(n)# DP solution.class Solution3(object):    def numTrees(self, n):        counts = [1, 1]        for i in xrange(2, n + 1):            count = 0            for j in xrange(i):                count += counts[j] * counts[i - j - 1]            counts.append(count)        return counts[-1]if __name__ == "__main__":    assert Solution().numTrees(3) == 5