Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
1 2 3 4 5 6 7 8 9 10
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
Difficulty: Medium
Code:
1 2 3 4 5
classSolution{ public List<List<Integer>> combine(int n, int k) { } }
题意
给定数字n和k,从数字1到n中返回k个数字到所有组合。
Solution 1
这种要求出所有结果的集合,一般都是用调用递归来解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution{ public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<List<Integer>>(); help(res,n,k,new ArrayList<Integer>(),1); return res; } privatevoidhelp(List<List<Integer>> res,int n, int k, List<Integer> cur, int start){ if(cur.size()==k){ res.add(new ArrayList<Integer>(cur)); return; } for(int i=start;i<=n;i++){ cur.add(i); help(res,n,k,cur,i+1); cur.remove(cur.size()-1); } } }