-
Notifications
You must be signed in to change notification settings - Fork 21
/
Permutations.swift
51 lines (44 loc) 路 1.09 KB
/
Permutations.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
// Permutations.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 05/12/2017.
// Copyright 漏 2017 lizhaotailang. All rights reserved.
//
// Given a collection of distinct numbers, return all possible permutations.
//
// For example,
// [1,2,3] have the following permutations:
// [
// [1,2,3],
// [1,3,2],
// [2,1,3],
// [2,3,1],
// [3,1,2],
// [3,2,1]
// ]
//
// Accepted. See [PermutationsTests](./LeetCodeTests/PermutationsTests.swift) for test cases.
//
import Foundation
class Permutations {
func permute(_ nums: [Int]) -> [[Int]] {
var results: [[Int]] = []
if nums.isEmpty {
return results
}
if nums.count == 1 {
results.append([nums[0]])
return results
}
let ints = Array(nums[0..<nums.count - 1])
for list in permute(ints) {
for i in 0...list.count {
var tmp = Array(list)
tmp.insert(nums[nums.count - 1], at: i)
results.append(tmp)
}
}
return results
}
}