leetcode -- 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     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 6         if(k == 0){
 7             return result;
 8         }
 9         
10         ArrayList<Integer> com = new ArrayList<Integer>();
11         int depth = 1;
12         generate(result, com, depth, n, k);
13         return result;
14     }
15     
16     public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> com,
17             int depth, int n, int k){
18                 if(com.size() == k){
19                     ArrayList<Integer> tmp = new ArrayList<Integer>();
20                     tmp.addAll(com);
21                     result.add(tmp);
22                     return;
23                 }
24                 
25                 for(int i = depth; i <= n; i++){
26                     com.add(i);
27                     generate(result, com, i + 1, n, k);
28                     com.remove(com.size() - 1);
29                 }
30                 
31             }
32 }

 

posted @ 2013-08-18 19:55  feiling  阅读(360)  评论(0编辑  收藏  举报