Very simple recursive solution in Swift


  • 0
    A

    The trick here, to make sure results are as expected, is to generate subsets for the set minus the last number, then create a copy appending the last number to all subsets, then return the union.

    class Solution {
        func subsets(_ nums: [Int]) -> [[Int]] {
            if nums.isEmpty { return [[]] }
            let last = nums.last!
            var left = nums
            left.removeLast()
            let leftSubs = subsets(left)
            return leftSubs + leftSubs.map {$0 + [last]}
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.