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 class Solution { 2 List<List<Integer>> ans = new ArrayList<List<Integer>>(); 3 public List<List<Integer>> combine(int n, int k) { 4 List<Integer> list = new ArrayList<>(); 5 combination(list,n,k,1); 6 return ans; 7 } 8 9 public void combination(List<Integer> list, int n, int k,int s){ 10 if(k == 0){ 11 List<Integer> tmp = new ArrayList<>(list); 12 ans.add(tmp); 13 return; 14 } 15 for(int i = s; i <= n; i++){ 16 list.add(i); 17 combination(list,n,k-1,i+1); 18 list.remove(list.size()-1); 19 } 20 } 21 }