Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 30, 2012 06:47
Show Gist options
  • Select an option

  • Save pdu/4411304 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4411304 to your computer and use it in GitHub Desktop.
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. http://www.leetcode.com/onlinejudge
class Solution {
public:
void dfs(vector<vector<int> >& ret, vector<int>& tmp, int n, int left, int k) {
if (k == 0) {
ret.push_back(tmp);
return;
}
for (int i = left; i <= n; ++i) {
tmp.push_back(i);
dfs(ret, tmp, n, i + 1, k - 1);
tmp.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
vector< vector<int> > ret;
vector<int> tmp;
dfs(ret, tmp, n, 1, k);
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment