本题利用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])
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(i): 12 dp[i] += dp[j]*dp[i-j-1] 13 14 return dp[n]
时间: 2024-10-10 21:25:08