Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Solution1:
better
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
combine(k, 0, n - k, result, new ArrayList<Integer>());
return result;
}
private void combine(int k, int begin, int end, List<List<Integer>> result, List<Integer> temp) {
if (k == 0) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = begin; i <= end; i++) {
temp.add(i + 1);
combine(k - 1, i + 1, end + 1, result, temp);
temp.remove(temp.size() - 1);
}
}
Solution2:
public List<List<Integer>> combine1(int n, int k) {
if (k == n || k == 0) {
List<Integer> row = new LinkedList<>();
for (int i = 1; i <= k; ++i) {
row.add(i);
}
return new LinkedList<>(Arrays.asList(row));
}
List<List<Integer>> result = combine(n - 1, k - 1);
result.forEach(e -> e.add(n));
result.addAll(combine(n - 1, k));
return result;
}