Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Have you met this question in a real interview? Yes ExampleFor example, If n = 4 and k = 2, a solution is: [[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
基础的DFS的题。
代码:
public List<List<Integer>> combine(int n, int k) { // write your code here List<List<Integer>> result = new ArrayList<>(); if(n<=0 || k<=0) return result; List<Integer> list = new ArrayList<>(); dfs(result, list, 1, n, k); return result; } private void dfs(List<List<Integer>> result, List<Integer> list, int start, int n, int k){ if(list.size() == k){ result.add(new ArrayList<Integer>(list)); } if(list.size()>k) return; for(int i=start;i<=n;i++){ list.add(i); dfs(result, list, i+1, n, k); list.remove(list.size()-1); } }