Combinations
Last updated
Last updated
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<>();
if (n == 0 || k == 0) {
return ans;
}
List<Integer> combination = new ArrayList<Integer>();
combineHelper(1, n, k, combination, ans);
return ans;
}
private void combineHelper(int start, int n, int k, List<Integer> combination, List<List<Integer>> ans) {
if (combination.size() == k) {
ans.add(new ArrayList<Integer>(combination));
return;
}
for (int i = start; i <= n; i++) {
combination.add(i);
combineHelper(i + 1, n, k, combination, ans);
combination.remove(combination.size() - 1);
}
}
}public class Solution {
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
public List<List<Integer>> combine(int n, int k) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
dfs(n, 1, k, new ArrayList<>(), result);
return result;
}
private void dfs(int n, int index, int k, List<Integer> list, List<List<Integer>> result) {
if (list.size() == k) {
result.add(new ArrayList<>(list));
return;
}
if (index > n) {
return;
}
list.add(index);
dfs(n, index + 1, k, list, result);
list.remove(list.size() - 1);
dfs(n, index + 1, k, list, result);
}
}