码迷,mamicode.com
首页 > 系统相关 > 详细

combination的eclipse运行结果

时间:2015-07-08 12:49:58      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

 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]]

 

combination的eclipse运行结果

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4629793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!