标签:利用 int tree div class ret range blog sel
本题利用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]
Leetcode 86. Unique Binary Search Trees
标签:利用 int tree div class ret range blog sel
原文地址:http://www.cnblogs.com/lettuan/p/6196887.html