forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Combinations.swift
42 lines (34 loc) · 990 Bytes
/
Combinations.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
/**
* Question Link: https://leetcode.com/problems/combinations/
* Primary idea: Classic Depth-first Search, another version of Subsets
*
* Time Complexity: O(n!), Space Complexity: O(n)
*
*/
class Combinations {
func combine(n: Int, _ k: Int) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
let nums = _init(n)
_dfs(nums, &res, &path, 0, k)
return res
}
private func _init(n: Int) -> [Int] {
var res = [Int]()
for i in 1 ... n {
res.append(i)
}
return res
}
private func _dfs(nums: [Int], inout _ res: [[Int]], inout _ path: [Int], _ index: Int, _ k: Int) {
if path.count == k {
res.append([Int](path))
return
}
for i in index ..< nums.count {
path.append(nums[i])
_dfs(nums, &res, &path, i + 1, k)
path.removeLast()
}
}
}