forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Permutations.swift
34 lines (29 loc) · 949 Bytes
/
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
/**
* Question Link: https://leetcode.com/problems/permutations/
* Primary idea: Classic Depth-first Search, remember backtracking
*
* Time Complexity: O(n^n), Space Complexity: O(n)
*
*/
class Permutations {
func permute(_ nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
var isVisited = [Bool](repeating: false, count: nums.count)
dfs(&res, &path, &isVisited, nums)
return res
}
private func dfs(_ res: inout [[Int]], _ path: inout [Int], _ isVisited: inout [Bool], _ nums: [Int]) {
guard path.count != nums.count else {
res.append(path)
return
}
for (i, num) in nums.enumerated() where !isVisited[i] {
path.append(num)
isVisited[i] = true
dfs(&res, &path, &isVisited, nums)
isVisited[i] = false
path.removeLast()
}
}
}