Leetcode-Combinations

LiBlog發表於2014-11-16

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],
]
Have you met this question in a real interview?
 
Analysis:
We need consider the boundary and the return condition very carefully!
 
Iterative Solution:
public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> resList = new LinkedList<List<Integer>>();
        if (k==0) return resList;
        
        LinkedList<Integer> numList = new LinkedList<Integer>();
        numList.addLast(0);
        while (!numList.isEmpty()){
            // increase the value of the last number
            int newLastNum = numList.peekLast()+1;
            if (newLastNum >= n-(k-numList.size())+1){
                // backtrack to the previous level.
                numList.pollLast();
            } else {
                numList.pollLast();
                numList.addLast(newLastNum);
                
                // Check if we have k numbers, then output current combination.
                if (numList.size()==k){
                    resList.add(new LinkedList<Integer>(numList));
                } else {
                    // push a new number into the list.
                    // The initial value is @newLastNum, as we always increase first at the begnning of every loop.
                    numList.addLast(newLastNum);
                }
            }
        }
        return resList;
    }
}

 

Solution:
 1 public class Solution {
 2     public List<List<Integer>> combine(int n, int k) {
 3         List<List<Integer>> resSet = new ArrayList<List<Integer>>();
 4         if (n==0 || k==0) return resSet;
 5         List<Integer> curList = new ArrayList<Integer>();
 6         combineRecur(resSet,curList,1,k,n,k);
 7         return resSet;     
 8     }
 9    
10     public void combineRecur(List<List<Integer>> resSet, List<Integer> curList, int curIndex, int numLeft, int n, int k){
11         if (numLeft==1){
12             for (int i=curIndex;i<=n;i++){
13                 curList.add(i);
14                 List<Integer> temp = new ArrayList<Integer>();
15                 temp.addAll(curList);
16                 resSet.add(temp);
17                 curList.remove(curList.size()-1);
18             }
19             return;
20         }
21        
22 
23         for (int i=curIndex;i<=n-numLeft+1;i++){
24             curList.add(i);
25             combineRecur(resSet,curList,i+1,numLeft-1,n,k);
26             curList.remove(curList.size()-1);
27         }
28     }
29         
30 }