Combinations

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     
 3     public static void main(String[] args) {
 4         System.out.println(combine(4, 2));
 5     }
 6     
 7     public static ArrayList<ArrayList<Integer>> combine(int n, int k) {
 8         ArrayList<Integer> list = new ArrayList<Integer>();
 9         ArrayList<ArrayList<Integer>> listsAll = new ArrayList<ArrayList<Integer>>();
10         allCombine(n, k, 1, list, listsAll);
11         return listsAll;
12     }
13     
14     public static void allCombine(int n, int k, int current, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> listsAll) {
15         if (current > n || list.size() >= k) return;
16         list.add(current);
17         if (list.size() == k) {
18             listsAll.add(new ArrayList<Integer>(list));
19         }
20         allCombine(n, k, current + 1, list, listsAll);
21         list.remove(list.size() - 1);
22         allCombine(n, k, current + 1, list, listsAll);        
23     }
24 }

转载请注明出处: cnblogs.com/beiyeqingteng/

posted @ 2015-01-06 08:53  北叶青藤  阅读(188)  评论(0)    收藏  举报