Wednesday, November 19, 2014

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

For what permutations and combinations are, this is a good explanation:

http://betterexplained.com/articles/easy-permutations-and-combinations/

This problem has been asked on the internet a lot.
http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n

Recursion and backtracking is a way to do it.

http://stackoverflow.com/questions/9552295/using-recursion-and-backtracking-to-generate-all-possible-combinations

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int>> res;
        if (n==0||k==0) return res;
        vector<int> path;
        bt(n, k, 1, 0, res, path);
        return res;
    }
   
    void bt(int n, int k, int start, int cur, vector<vector<int>> &r, vector<int> &p)
    {
        if (k==cur)
        {
            r.push_back(p);
            return;
        }
        else
        {
            for (int i=start; i<=n; i++)
            {
                p.push_back(i);
                bt(n,k,i+1,cur+1, r, p);
                p.pop_back();
            }
        }
    }
};


TO add iterative solution later.

No comments:

Post a Comment