Skip to content

Commit 99eee62

Browse files
authored
Merge pull request neetcode-gh#1132 from Mahim1997/dev/46_swift
46. Permutations
2 parents db621ea + 8741ce8 commit 99eee62

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

swift/46-Permutations.swift

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
var ans: [[Int]] = []
3+
4+
func permute(_ nums: [Int]) -> [[Int]] {
5+
var referenceNums = nums
6+
dfs(start: 0, currentOrder: &referenceNums)
7+
return ans
8+
}
9+
}
10+
11+
private extension Solution {
12+
private func swap(_ arr: inout [Int], at i1: Int, with i2: Int) {
13+
guard
14+
i1 < arr.count,
15+
i2 < arr.count
16+
else { return }
17+
18+
let temp = arr[i1]
19+
arr[i1] = arr[i2]
20+
arr[i2] = temp
21+
}
22+
23+
func dfs(start: Int, currentOrder nums: inout [Int]) {
24+
// base case [take into final answer]
25+
if start == nums.count {
26+
ans.append(nums)
27+
return
28+
}
29+
30+
// for each idx, take, switch with start, backtrack, switch back
31+
for i in start..<nums.count {
32+
// choose i.e. take it
33+
swap(&nums, at: i, with: start)
34+
35+
// backtrack (from next idx)
36+
dfs(start: start + 1, currentOrder: &nums)
37+
38+
// unchoose i.e. remove it
39+
swap(&nums, at: start, with: i)
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)