LeetCode – 46. Permutations

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

法ㄧ: (Recursive)

func perm(nums: [Int]) -> [[Int]] {
    var result: [[Int]] = []
    permHelper(nums, [], &result)
    return result
}


func permHelper(_ nums: [Int], _ accumArr: [Int], _ result: inout [[Int]]) {
    if nums.count == 1 { result.append(accumArr + nums) }
    for i in 0 ..< nums.count {
        var newArr = nums
        newArr.remove(at: i)
        permHelper(newArr, accumArr + [nums[i]], &result)
    }
}

法二:(Iterative) 參考自Ref

func permute(_ nums: [Int]) -> [[Int]] {
    guard !nums.isEmpty else { return [] }
    var result: [[Int]] = [[]]
    for item in nums {
        var tmp: [[Int]] = []
        for i in 0 ..< result.count {
            for j in 0 ... result[i].count {
                var tmpArr = result[i]
                tmpArr.insert(item, at: j)
                tmp.append(tmpArr)
            }
        }
        result = tmp
    }
    return result
}

Ref: https://leetcode.com/problems/permutations/discuss/558360/General-Iterative-Approach-with-Queue-in-Swift