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:
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
Answer:
public List<List<Integer>> combine(int n, int k) {
List<Integer> subres = new ArrayList<Integer>();
List<List<Integer>> res = new ArrayList<List<Integer>>();
DFS(subres, res, n, k, 1);
return res;
}
public void DFS(List<Integer> subres, List<List<Integer>> res, int n, int k, int start){
if(subres.size()==k){
List<Integer> newsubres = new ArrayList<Integer>(subres);
res.add(newsubres);
return;
}
for(int i=start; i<=n; ++i){
subres.add(i);
DFS(subres, res, n, k, i+1);
subres.remove(subres.size()-1);
}
return;
}
No comments:
Post a Comment