## 题目地址

https://leetcode.com/problems/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>> res;
vector<int> out;
helper(n, k, 1, out, res);
return res;
}
void helper(int n, int k, int level, vector<int>& out, vector<vector<int>>& res) {
if (out.size() == k) {res.push_back(out); return;}
for (int i = level; i <= n; ++i) {
out.push_back(i);
helper(n, k, i + 1, out, res);
out.pop_back();
}
}
};

``````

1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5

C(4, 2) = C(3, 1) + C(3, 2)

``````class Solution {
public:
vector<vector<int>> combine(int n, int k) {
if (k > n || k < 0) return {};
if (k == 0) return {{}};
vector<vector<int>> res = combine(n - 1, k - 1);
for (auto &a : res) a.push_back(n);
for (auto &a : combine(n - 1, k)) res.push_back(a);
return res;
}
};

``````

``````0 0 #initialization
1 0
1 1
1 2 #push_back
1 3 #push_back
1 4 #push_back
1 5
2 5
2 2
2 3 #push_back
2 4 #push_back
...
3 4 #push_back
3 5
4 5
4 4
4 5
5 5 #stop

``````

``````class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> out(k, 0);
int i = 0;
while (i >= 0) {
++out[i];
if (out[i] > n) --i;
else if (i == k - 1) res.push_back(out);
else {
++i;
out[i] = out[i - 1];
}
}
return res;
}
};
``````

评论
0 评论