forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0046-permutations.swift
42 lines (35 loc) · 1.09 KB
/
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
37
38
39
40
41
42
classSolution{
varans:[[Int]]=[]
func permute(_ nums:[Int])->[[Int]]{
varreferenceNums= nums
dfs(start:0, currentOrder:&referenceNums)
return ans
}
}
privateextensionSolution{
privatefunc swap(_ arr:inout[Int], at i1:Int, with i2:Int){
guard
i1 < arr.count,
i2 < arr.count
else{return}
lettemp=arr[i1]
arr[i1]=arr[i2]
arr[i2]= temp
}
func dfs(start:Int, currentOrder nums:inout[Int]){
// base case [take into final answer]
if start == nums.count {
ans.append(nums)
return
}
// for each idx, take, switch with start, backtrack, switch back
foriin start..<nums.count {
// choose i.e. take it
swap(&nums, at: i, with: start)
// backtrack (from next idx)
dfs(start: start +1, currentOrder:&nums)
// unchoose i.e. remove it
swap(&nums, at: start, with: i)
}
}
}