码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--Combinations

时间:2014-06-08 08:08:29      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   java   a   

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
    /**This code is an implemenatation of bfs idea.<br>
     * @author Averill Zheng
     * @version 2014-06-05
     * @since JDK 1.7
     */
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer> > combinations = new ArrayList<List<Integer> >();
        if(k > 0){
            for(int i = 0; i < n; ++i){
                List<Integer> aList = new ArrayList<Integer>();
                aList.add(i + 1);
                combinations.add(aList);
            }
            if(k > 1){
                for(int j = 1; j < k; ++j){ //j denotes the number of integer in each list
                    List<List<Integer>> temp = new ArrayList<List<Integer> >();
                    int length = combinations.size();
                    for(int l = 0; l < length; ++l){
                        List<Integer> aList = combinations.get(l);
                        int lastNumber = aList.get(j - 1);
                        if(n - lastNumber >= k - j){ // has enough number to get the k combinations
                            for(int m = lastNumber + 1; m <= n; ++m){
                                List<Integer> newList = new ArrayList<Integer>();
                                newList.addAll(aList);
                                newList.add(m);
                                temp.add(newList);
                            }
                        }
                    }
                    combinations = temp;
                }
            }
        }  
        return combinations;   
    }
}

  

leetcode--Combinations,布布扣,bubuko.com

leetcode--Combinations

标签:c   class   blog   code   java   a   

原文地址:http://www.cnblogs.com/averillzheng/p/3773977.html

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