###### [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-排列|递归|非递归|Java|Python

2016-06-02 10:43:01

#### LeetCode 77. Combinations 解题报告

2016-02-18 14:03:18

#### <LeetCode OJ> 77. Combinations

2016-03-09 15:35:14

#### LeetCode77——Combinations

2015-11-17 21:21:10

#### 【LEETCODE】77-Combinations [Python]

2016-01-07 16:57:28

#### LeetCode（77） Combinations

2015-09-17 20:30:07

#### [leetcode-７７]Combinations(java)

2015-08-05 20:57:03

#### Leetcode-77_ Combinations(组合)-深搜解法-【C++】

2018-03-21 21:56:41

#### LeetCode 77 Combinations (Python详解及实现)

2017-08-08 13:50:46

#### 77 Combinations

2015-10-25 16:20:02

## 不良信息举报

[leetcode] 77. Combinations