Last active
January 1, 2016 14:19
-
-
Save safeng/8156755 to your computer and use it in GitHub Desktop.
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],]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void comb(int start, int idx, int k, int n, vector<int> & sol, vector<vector<int> > & res) | |
{ | |
if(idx == k) | |
{ | |
res.push_back(sol); | |
}else | |
{ | |
for(int i = start; i<n; ++i) // never look before is a way to avoid duplicates | |
{ | |
sol.push_back(i+1); | |
comb(i+1, idx+1, k, n, sol, res); // never look before means starting from selected next | |
sol.pop_back(); // cancel result | |
} | |
} | |
} | |
vector<vector<int> > combine(int n, int k) { | |
vector<vector<int> > res; | |
if(k>n || n == 0) | |
return res; | |
vector<int> sol; | |
comb(0, 0, k, n, sol, res); | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment