-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0046.Permutations.swift
36 lines (31 loc) · 985 Bytes
/
0046.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
class Solution {
func permute(_ nums: [Int]) -> [[Int]] {
let n = nums.count
let sub = Array(repeating: 0, count: n)
var result = [[Int]]()
cycle(0, n, nums, sub, &result)
return result
}
private func cycle(_ step: Int, _ n: Int, _ candidates: [Int], _ sub: [Int], _ result: inout [[Int]]) {
if step == n-1 {
for c in candidates {
var s = sub
s[step] = c
result.append(s)
}
return
}
for c in candidates {
var s = sub
s[step] = c
var newCandidates = getCandidates(candidates, c)
cycle(step+1, n, newCandidates, s, &result)
}
}
private func getCandidates(_ nums: [Int], _ exclude: Int) -> [Int] {
var nums = nums
let idx = nums.firstIndex(of: exclude)!
nums.remove(at: idx)
return nums
}
}