All posssible k combinations of numbers out of 1 to n (Combinations)

Given two integers n and k, return all possible combinations of k numbers out of 1 \dots n.
INPUT: n = 4, k = 2
OUTPUT: [[2,4], [3,4], [2,3], [1,2], [1,3], [1,4]]

Thoughts:
Using recursion and backtracking. We keep adding elements recursively until the size of partial solution exceeds k.

Code (C++):

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<int> partial;
        vector<vector<int> > sol;
        combineRecursion(n, k, partial, sol);
        return sol;
    }
    
    void combineRecursion(int n, int k, vector<int> partial,
        vector<vector<int> >& sol) {
        if(partial.size() == k) {
            if(find(sol.begin(), sol.end(), partial) == sol.end()) {
                sort(partial.begin(), partial.end());
                sol.push_back(partial);
            }
        } else if(partial.size() > k) {
            return;
        } else {
            for(int i = n; i >= 1; --i) {
                vector<int> partial_sol(partial);
                partial_sol.push_back(i);
                combineRecursion(i-1, k, partial_sol, sol);
            }
        }
    }
};

Code (Java):

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    public ArrayList<ArrayList<Integer>> combine(int n, int k) {
        ArrayList<ArrayList<Integer>> sol = new ArrayList<ArrayList<Integer>>();
        recursion(n,k,new ArrayList<Integer>(), sol);
        return sol;
    }
    
    private void recursion(int n, int k, ArrayList<Integer> partial,
        ArrayList<ArrayList<Integer>> sol) {
        if(partial.size() == k && !sol.contains(partial)) {
            Collections.sort(partial);
            sol.add(partial);
        } else if(partial.size() > k) {
            return;
        } else {
            for(int i = n; i >= 1; --i) {
                ArrayList<Integer> partial_sol = new ArrayList<Integer>();
                partial_sol.addAll(partial);
                partial_sol.add(i);
                recursion(i-1, k, partial_sol, sol);
            }
        }
    }
}
Advertisements

1 Comment (+add yours?)

  1. Ravi
    Dec 12, 2013 @ 01:38:11

    Good Solution.Thanks

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: