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], ]
Subscribe to see which companies asked this question.
Solution:
Tips:
recursion
Java Code:
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<Integer> curLst = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
combine(n, 1, k, curLst, result);
return result;
}
public void combine(int n, int begin, int k, List<Integer> curLst, List<List<Integer>> result) {
if (0 == k){
result.add(new ArrayList(curLst));
return;
}
for (int i = begin; i <= n; i++) {
curLst.add(i);
combine(n, i + 1, k - 1, curLst, result);
curLst.remove(curLst.size() - 1);
}
}
}