在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 }
|
请发表评论