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], ]
这道题用dfs很清晰,我犯了个错误就是忘了用一个参数去控制现在添加了几个数, 代码中的current就是这个作用,当current大于k的时候,说明我们已经添加了k个数了,那么就将这个结果添加到结果集里面. 或者更好的办法是,不用current, 当sub.size()=k的时候,那说明sub这个arraylist子结果集已经有了k个数了,就可以返回了
public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> result= new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> sub= new ArrayList<Integer>(); if(n<k||k==0) return result; dfs(result,sub, n, k, 1,1); return result; } public void dfs(ArrayList<ArrayList<Integer>> result,ArrayList<Integer> sub, int n, int k, int start, int current){ if(current>k) { result.add(new ArrayList<Integer>(sub)); return; } for(int i=start;i<=n;i++){ sub.add(i); dfs(result, sub, n, k, i+1,current+1); sub.remove(sub.size()-1); } }