forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinations.swift
More file actions
29 lines (24 loc) · 751 Bytes
/
Combinations.swift
File metadata and controls
29 lines (24 loc) · 751 Bytes
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
/**
* Question Link: https://leetcode.com/problems/combinations/
* Primary idea: Classic Depth-first Search, another version of Subsets
*
* Time Complexity: O(2^n), Space Complexity: O(n)
*
*/
class Combinations {
func combine(_ n: Int, _ k: Int) -> [[Int]] {
var res = [[Int]](), path = [Int]()
dfs(&res, &path, 0, Array(1...n), k)
return res
}
private func dfs(_ res: inout [[Int]], _ path: inout [Int], _ idx: Int, _ nums: [Int], _ k: Int) {
if path.count == k {
res.append(path)
}
for i in idx..<nums.count {
path.append(nums[i])
dfs(&res, &path, i + 1, nums, k)
path.removeLast()
}
}
}