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],
]
这道题完全是凭着感觉A出来的
 1 public class Solution {
 2     private List<List<Integer>> result = new ArrayList<List<Integer>>();
 3     
 4     public List<List<Integer>> combine(int n, int k) {
 5         List<Integer> cur = new ArrayList<Integer>();
 6         
 7         getResult(cur, 1, 0, k, n);
 8        
 9         return result;
10     }
11     public void getResult(List<Integer> cur, int start, int dep, int depMax, int end){
12         if(dep == depMax){
13             List<Integer> temp = new ArrayList<Integer>(cur);
14             result.add(temp);
15         }else{
16             for(int i = start; i <= end; i++){
17                 cur.add(i);
18                 getResult(cur, i + 1, dep + 1, depMax, end);
19                 cur.remove(cur.size() - 1);
20             }
21         }
22     }
23 }

 

posted on 2015-01-11 00:46  luckygxf  阅读(171)  评论(0编辑  收藏  举报

导航