https://leetcode.com/problems/unique-binary-search-trees-ii/

class Solution {
    func generateTrees(_ n: Int) -> [TreeNode?] {
        guard n > 0 else { return [] }
        return intToBST(Array(1...n))
    }

    func intToBST(_ nums: [Int]) -> [TreeNode?] {
        guard nums.count > 0 else { return [nil] }
        var res = [TreeNode?]()
        for i in 0..<nums.count {
            let left = intToBST(Array(nums[0..<i]))
            let right = i == nums.count - 1 ? [nil] : intToBST(Array(nums[i+1..<nums.count]))
            for m in 0..<left.count {
                for n in 0..<right.count {
                    let node = TreeNode(nums[i])
                    node.left = left[m]
                    node.right = right[n]
                    res.append(node)
                }
            }
        }
        return res
    }
}

原本在intToBST中有一段代码guard nums.count > 1 else { return [TreeNode(nums[0])] }去掉之后直接从44ms提升到了32ms,不知道是影响了性能,还是只是多次运行结果本来可能会有毫秒级的时间差别。

Runtime: 32 ms, faster than 100.00% of Swift online submissions for Unique Binary Search Trees II.
Memory Usage: 20.4 MB, less than 50.00% of Swift online submissions for Unique Binary Search Trees II.