LeetCode – 78. Subsets

題目連結: https://leetcode.com/problems/subsets/

參考解法: https://leetcode.com/problems/subsets/discuss/27337/Simple-Fast-and-Short-Swift-Solution(Beat-97.3)

法ㄧ(Recursive version):

func subsets(_ nums: [Int]) -> [[Int]] {
    var result: [[Int]] = []
    var arr: [Int] = []
    for i in 0 ... nums.count {
        helper(i, nums, 0, &arr, &result)
    }
    return result
}

func helper(_ steps: Int, _ nums: [Int], _ start: Int, _ arr: inout [Int], _ result: inout [[Int]]) {
    if arr.count == steps {
        result.append(arr)
        return
    }
    if start >= nums.count {
        return
    }
    for i in start ..< nums.count {
        arr.append(nums[i])
        helper(steps, nums, i + 1, &arr, &result)
        arr.removeLast()
    }
}

法二(Iterative version):

func subsets(_ nums: [Int]) -> [[Int]] {
    var result: [[Int]] = []
    for i in 0 ..< nums.count {
        for j in 0 ..< result.count {
            let tmp = result[j] + [nums[i]]
            result.append(tmp)
        }
        result.append([nums[i]])
    }
    result.append([])
    return result
}