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], ]
Analysis: DFS. The if clause in for loop is a little bit tricky. It should be start at the end of that list of numbers of and add new integer to tem only when i >= k-tem.size().
public class Solution {
public void combine(int n, int k, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tem) {
if(tem.size()==k || n==0) {
ArrayList<Integer> clone = new ArrayList<Integer>(tem);
Collections.sort(clone);
res.add(clone);
return;
}
for(int i=n; i>=1; i--) {
if(i >= k-tem.size()) {
tem.add(i);
combine(i-1, k, res, tem);
tem.remove(tem.size()-1);
}
}
return;
}
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tem = new ArrayList<Integer>();
combine(n, k, res, tem);
return res;
}
}
Update: 30/01/2014
public class Solution {
public void combine(int n, int k, int current, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tem) {
if(tem.size() == k) {
ArrayList<Integer> clone = new ArrayList<Integer>(tem);
res.add(clone);
return;
}
for(int i=current; i<=n; i++) {
tem.add(i);
combine(n, k, i+1, res, tem); // should be i+1, not current+1
tem.remove(tem.size()-1);
}
return;
}
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tem = new ArrayList<Integer>();
combine(n, k, 1, res, tem);
return res;
}
}