96. Unique Binary Search Trees

这一题用了卡特兰数,
96. Unique Binary Search Trees_第1张图片
微信图片_20180703142700.jpg

代码如下:

class Solution(object):
    def numTrees(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp = [1,1,2]
        if n <= 2:
            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]

你可能感兴趣的:(96. Unique Binary Search Trees)