首页 > 代码库 > [leetcode] Unique Binary Search Trees @ Python
[leetcode] Unique Binary Search Trees @ Python
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
题目大意很简单,就是计算有多少个不同的二叉寻找树满足前序遍历是1,2,3...n的条件
思路:每一棵树都是由根节点,左子树,右子树构成,一旦确定根节点是x的同时,
左子树只能由1,2,3...x-1构成,同理右子树由x+1,x+2...n构成,可以
[方法1]跌代求解;
class Solution: # @return an integer def numTrees(self, n): dp = [1, 1, 2] if n < 3: 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]
[方法2]递归求解
class Solution: # @return an integer def numTrees(self, n): dp = [1, 1, 2] if n < 3: return dp[n] ans = 0 for i in range(n): ans += self.numTrees(i)*self.numTrees(n-i-1) return ans
[leetcode] Unique Binary Search Trees @ Python
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。