加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift]LeetCode96. 不同的二叉搜索树 | Unique Binary Search T

发布时间:2020-12-14 05:09:58 所属栏目:百科 来源:网络整理
导读:Given? n ,how many structurally unique?BST‘s?(binary search trees) that store values 1 ...? n ? Example: Input: 3Output: 5Explanation: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 给定一个

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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读