-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0077Combinations.java
61 lines (51 loc) · 1.69 KB
/
_0077Combinations.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.heatwave.leetcode.problems;
import java.util.ArrayList;
import java.util.List;
public class _0077Combinations {
static class Solution {
List<Integer> temp = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(1, n, k);
return ans;
}
private void backtracking(int start, int end, int k) {
if (temp.size() + (end - start + 1) < k) {
return;
}
if (temp.size() == k) {
ans.add(new ArrayList<>(temp));
return;
}
temp.add(start);
backtracking(start + 1, end, k);
temp.remove(temp.size() - 1);
backtracking(start + 1, end, k);
}
}
static class AnotherSolution {
List<Integer> temp = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(1, n, k);
return ans;
}
private void backtracking(int start, int end, int k) {
if (temp.size() == k) {
ans.add(new ArrayList<>(temp));
return;
}
for (int i = start; i <= end; i++) {
temp.add(i);
backtracking(i + 1, end, k);
temp.remove(temp.size() - 1);
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
solution.combine(4, 2);
AnotherSolution anotherSolution = new AnotherSolution();
anotherSolution.combine(4, 2);
}
}