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了。
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> results = new ArrayList<List<Integer>>(); if(k<0 || k>n) return results; List<Integer> result = new ArrayList<Integer>(); dfs(results, result, n, k, 1); return results; } public void dfs(List<List<Integer>> results, List<Integer> result, int n, int k, int start){ if(result.size()==k){ results.add(new ArrayList<Integer>(result)); return; } for(int i=start; i<=n; i++){ //加入结果 result.add(i); //往后搜索 dfs(results, result, n, k, i+1); //恢复现场 result.remove(result.size()-1); } } }