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], ]
Subscribe to see which companies asked this question
给定一个整型数n,对应一个序列{ 1, 2, …, n },给定一个整型数k,从该序列中任取k个数,组合为一个序列,求出所有序列。
使用回溯法解决,每次遍历选择元素时从i(i = m)位置到n,之后再进入递归,从i + 1位置到n,这样就能保证前面选过的不会再被选中,[1, 2]与[2, 1]是一样的情况,属于重复的,在结果中要去除这种重复情况。具体代码如下:
void backtrace(int n, int m, int k, int l, vector<int> &rec,
vector<vector<int>> &res)
{
if (l == k) {
res.push_back(rec);
return ;
}
else if (m > n) {
return ;
}
int i;
for (i = m; i <= n; ++i) {
rec.push_back(i);
dfs(n, i + 1, k, l + 1, rec, res);
rec.pop_back();
}
}
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> rec;
dfs(n, 1, k, 0, rec, res);
return res;
}
};