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 public ArrayList<ArrayList<Integer>> combine(int n, int k) { 3 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 4 get(n,k,1,new ArrayList<Integer>(),res); 5 return res; 6 } 7 public void get(int n,int k,int start,ArrayList<Integer>output,ArrayList<ArrayList<Integer>>res){ 8 if(output.size()==k){ 9 ArrayList<Integer> temp = new ArrayList<Integer>(); 10 temp.addAll(output); 11 res.add(temp); 12 return; 13 } 14 for(int i=start;i<=n;i++){ 15 output.add(i); 16 get(n,k,i+1,output,res); 17 output.remove(output.size()-1); 18 } 19 } 20 }