LeetCode 46. Permutations

题目

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]  
Output:  
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

思路

很常见的permutation题目,就是把所有可能性iterate一遍 参考YouTube1 参考YouTube2

Swift 题解

func permute(_ nums: [Int]) -> [[Int]] {  
        var result = [[Int]]()

        let current = [Int]()
        var dict = [String: Bool]()

        helper(current: current, left: nums.sorted(), index: 0, dict: &dict, result: &result)

        return result
    }

    func helper(current: [Int], left: [Int], index: Int, dict: inout [String: Bool], result: inout [[Int]]) {
        if left.isEmpty {
            result.append(current)
            return
        }

        for (cIndex, value) in left.enumerated() {
            var next = current
            next.append(value)
            var copy = left
            copy.remove(at: cIndex)
            helper(current: next, left: copy, index: index + 1, dict: &dict, result: &result)
        }
    }

chenbo

编程爱好者

Singapore