首页 > 系统服务 > 详细

combination的eclipse运行结果

时间:2015-07-08 12:49:23      阅读:152      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!