Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example
For example,
If n = 4 and k = 2, a solution is:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
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) {
if(k > n) return null;
List<List<Integer>> res = new ArrayList<List<Integer>>();
helper(res, new ArrayList<Integer>(), n, k, 1);
return res;
}
void helper(List<List<Integer>> res, List<Integer> list, int n, int k, int index) {
if(k == 0){
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = index; i <= n; i++) {
list.add(i);
helper(res, list, n, k - 1, i + 1);
list.remove(list.size() - 1);
}
}
}