1 import java.util.ArrayList; 2 import java.util.Arrays; 3 4 5 public class Combination { 6 7 public static ArrayList<ArrayList<Integer>> combine(int n, int k) { 8 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 9 if(n <= 0||n < k) 10 return res; 11 ArrayList<Integer> item = new ArrayList<Integer>(); 12 dfs(n,k,1,item, res);//because it need to begin from 1 13 return res; 14 } 15 16 private static void dfs(int n, int k, int start, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> res){ 17 if(item.size()==k){ 18 res.add(new ArrayList<Integer>(item));//because item is ArrayList<T> so it will not disappear from stack to stack 19 System.out.println(item); 20 return; 21 } 22 for(int i=start;i<=n;i++){ 23 System.out.println(i); 24 item.add(i); 25 dfs(n,k,i+1,item,res); 26 System.out.println(i); 27 item.remove(item.size()-1); 28 System.out.println(item); 29 30 } 31 } 32 33 public static void main(String[] args) 34 { 35 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 36 res=combine(3,2); 37 System.out.println(res); 38 39 } 40 41 }
1 2 [1, 2] 2 [1] 3 [1, 3] 3 [1] 1 [] 2 3 [2, 3] 3 [2] 2 [] 3 3 [] [[1, 2], [1, 3], [2, 3]]
时间: 2024-09-07 05:36:50