# [leetcode] 77. 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], ]

class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int>> rst;
vector<int> curRst;

if(k > 0 && n >= k)
​    ​    ​getCombine(rst, curRst, 0, 0, n, k);

return rst;
}

void getCombine(vector<vector<int>> &rst, vector<int> &curRst, int pos, int cnt, int n, int k) {
if(cnt == k) rst.push_back(curRst);
else {
if(n-pos < k-cnt-1) return;
else {
while(pos < n) {
curRst.push_back(pos+1);
pos++;
cnt++;
getCombine(rst, curRst, pos, cnt, n, k);
cnt--;
curRst.pop_back();
}
}
}
}
};

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> rst1, rst2;

if(n<k || k<0) return rst1;
if(n==k || k==0) {
vector<int> curRst;
for(int i=1; i<=k; i++) curRst.push_back(i);
rst1.push_back(curRst);
return rst1;
}

rst1 = combine(n-1, k-1);
for(int i=0; i<rst1.size(); i++)
​    ​    ​rst1[i].push_back(n);

rst2 = combine(n-1, k);

copy(rst2.begin(), rst2.end(), back_inserter(rst1));

return rst1;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode] 77. Combinations 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)