Leetcode 86. 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.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
本题利用BST的特性来用DP求解。由于BST的性质,所以root左子树的node全部<root。而右子树的node全部>root。
左子树 = [1, j-1], root = j, 右子树 = [j+1, n]
dp[n] = sum(dp[j - 1] * dp[n - j])
1 def numTrees(self, n): 2 """ 3 :type n: int 4 :rtype: int 5 """ 6 dp = [0]*(n+1) 7 dp[0] = 1 8 dp[1] = 1 9 10 for i in range(2, n+1): 11 for j in range(1,i+1): 12 dp[i] += dp[j-1]*dp[i-j] 13 14 return dp[n]