[Swift]LeetCode96. 不一樣的二叉搜索樹 | Unique Binary Search Trees

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pozpijle-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?git

Example:github

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 爲節點組成的二叉搜索樹有多少種?微信

示例:app

輸入: 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 }

20msspa

 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 }
相關文章
相關標籤/搜索