[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]
]

Analyse:

Solution:

class Solution {
    
    func permute(_ nums: [Int]) -> [[Int]] {
        var output: [[Int]] = [];
        var array: [Int] = [];
        
        permall(nums: nums, array: array, output: &output)
        
        return output;
    }
    
    func permall(nums: [Int], array: [Int], output: inout [[Int]]) {
        if(nums.count == 0) {
           // array.append(nums[0]);  
           // print("array: \(array)");
            output.append(array);
        }
        else {
            for i in 0..<(nums.count) {
                var newArray = array
                newArray.append(nums[i]);   
                var newNums = nums
                newNums.remove(at: i);
                permall(nums: newNums, array: newArray, output: &output)
            }
        }
    }
}

Last updated