leetcode 69: Combinations

Apr 18 '12

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],
]

 

 

public class Solution {
    public ArrayList<ArrayList<Integer>> combine(int n, int k) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> rel = new ArrayList<ArrayList<Integer>>();  
        ArrayList<Integer> temp = new ArrayList<Integer>();  
        
        subsetsRec(rel, temp, n, k, 0);   
          
        return rel;  
    }
    
    private void subsetsRec(ArrayList<ArrayList<Integer>> rel, ArrayList<Integer> temp, int n, int k, int level){
        if(temp.size() == k) {
            rel.add(new ArrayList<Integer>(temp) );
            return;
        }
        
        for(int i=level; i<n; i++) {
            temp.add( i+1 );
            
            subsetsRec(rel, temp, n, k, i+1);
            
            temp.remove(temp.size() -1);
        }
    }
}


 

posted @ 2013-02-10 05:38  西施豆腐渣  阅读(136)  评论(0编辑  收藏  举报