Combinations
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], ]
思路一:
深度优先遍历。
1 public List<List<Integer>> combine(int n, int k) { 2 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 3 dfs(ret, new ArrayList<Integer>(), n, k, 1); 4 return ret; 5 } 6 public void dfs(List<List<Integer>> ret, List<Integer> path, int n, int k, int start) { 7 8 if(path.size() == k) { 9 ret.add(new ArrayList<Integer>(path)); 10 return; 11 } 12 for(int i=start; i<=n; i++) { 13 path.add(i); 14 // 注意,最后一个参数是i + 1,不是start + 1!! 15 dfs(ret, path, n, k, i+1); 16 path.remove(path.size()-1); 17 } 18 19 }