-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathleetcode_0077_Combinations.java
More file actions
29 lines (25 loc) · 955 Bytes
/
leetcode_0077_Combinations.java
File metadata and controls
29 lines (25 loc) · 955 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
// AC: Runtime: 18 ms, faster than 62.24% of Java online submissions for Combinations.
// Memory Usage: 53.6 MB, less than 5.33% of Java online submissions for Combinations.
// backtracking.
// T:O(C(n, k)), S:O(C(n, k) * k)
//
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ret = new LinkedList<>();
List<Integer> temp = new LinkedList<>();
backtracking(n, k, temp, ret, 1);
return ret;
}
public void backtracking(int n, int k, List<Integer> path, List<List<Integer>> out, int startIndex) {
List<Integer> pathCopy = new LinkedList<>(path);
if (path.size() == k) {
out.add(pathCopy);
return;
}
for (int i = startIndex; i <= n + pathCopy.size() - k + 1; i++) {
pathCopy.add(i);
backtracking(n, k, pathCopy, out, i + 1);
pathCopy.remove(pathCopy.size() - 1);
}
}
}