LeetCode96. Unique Binary Search Trees
阿新 • • 發佈:2018-06-03
int umt obj 時間 組合 count class 問題 XA
題目:
Given n, how many structurally unique BST‘s (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: 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
思路:
這個問題可以被拆分,若選取值i為根節點,則1,2,...,i - 1為左子樹上的點,i + 1, i + 2, ..., n為右子樹上的點(由搜索二叉樹的性質可得)。而取i為根節點的組合數應為左子樹的種類數*右子樹的種類數。由此可以拆分,得到下邊這種直接叠代的代碼:
1 class Solution(object): 2 def numTrees(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 if n < 1: 8 return 0 9 return self.count_tree(1, n) 10 11 def count_tree(self, left, right): 12 if left >= right:13 return 1 14 res = 0 15 for i in range(left, right + 1): 16 res += self.count_tree(left, i - 1) * self.count_tree(i + 1, right) 17 return res
提交後顯示運行時間超時。原來是代碼中有太多重復叠代,如同求解斐波那契數列時的直接叠代解法。因此使用從底向上的解法:
class Solution(object): def numTrees(self, n):""" :type n: int :rtype: int """ if n < 1: return 0 trees = [0 for _ in range(n + 1)] trees[0], trees[1] = 1, 1 for i in range(2, n + 1): for j in range(1, i + 1): trees[i] += trees[j - 1] * trees[i - j] return trees[n]
順利通過~
LeetCode96. Unique Binary Search Trees