[Swift]LeetCode96. 不同的二叉搜索树 | Unique Binary Search Trees
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9936994.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
8ms
1 class Solution { 2 func numTrees(_ n: Int) -> Int { 3 if n <= 1 { 4 return 1 5 } 6 var dp = [Int](repeatElement(0, count: n + 1)) 7 8 dp[0] = 1 9 dp[1] = 1 10 11 for i in 2...n { 12 for j in 1...i { 13 dp[i] += dp[j - 1] * dp[i - j] 14 } 15 } 16 17 return dp[n] 18 } 19 }
20ms
1 class Solution { 2 func numTrees(_ n: Int) -> Int { 3 guard n >= 1 else { 4 return 0 5 } 6 7 var sum = [0, 1, 2, 5] 8 9 if n < sum.count { 10 return sum[n] 11 } 12 13 for i in 4...n { 14 var val = 0 15 for k in 0..<i { 16 if sum[k] == 0 || sum[i-1-k] == 0 { 17 val += sum[k] + sum[i-1-k] 18 } 19 else { 20 val += sum[k] * sum[i-1-k] 21 } 22 } 23 sum.append(val) 24 } 25 26 return sum.last! 27 } 28 }