Given two integersnandk, return all possible combinations ofknumbers out of 1 ...n.
For example,
Ifn= 4 and k= 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
2. Implementation
(1) Backtracking
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> combination = new ArrayList<>();
getCombinations(1, n, k, combination, res);
return res;
}
public void getCombinations(int start, int n, int k, List<Integer> combination, List<List<Integer>> res) {
if (k == 0) {
res.add(new ArrayList<>(combination));
return;
}
for (int i = start; i <= n; i++) {
combination.add(i);
getCombinations(i + 1, n, k - 1, combination, res);
combination.remove(combination.size() - 1);
}
}
}