Leetcode练习(Python):动态规划类:第96题:不同的二叉搜索树:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
题目:
不同的二叉搜索树:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
思路:
找规律,使用动态规划模板。
程序:
class Solution:
def numTrees(self, n: int) -> int:
if n <= 0:
return 0
auxiliary = [1] * (n + 1)
for index in range(2, n + 1):
auxiliary_result = 0
index1 = 0
index2 = index - 1
while index1 < index2:
auxiliary_result += 2 * auxiliary[index1] * auxiliary[index2]
index1 += 1
index2 -= 1
if index1 == index2:
auxiliary_result += auxiliary[index1] * auxiliary[index2]
auxiliary[index] = auxiliary_result
return auxiliary[-1]
浙公网安备 33010602011771号