【发布时间】:2020-11-22 10:45:32
【问题描述】:
我想生成一个向量的向量组合。 例如:如果
std::vector<std::vector<int>> arr = {{1,2},{1,3},{1,4},{1,5}}
Comb(arr, 2) 应返回:
{
{{1,2},{1,3}},{{1,2},{1,4}}, {{1,2},{1,5}}, {{1,3},{1,4}}, {{1,3},{1,5}}, {{1,4},{1,5}}
}
(即将向量视为需要组合的对象)
下面的代码对整数进行组合,我相信我可以通过修改此代码得到我需要的:例如。通过开始将函数类型更改为 vector
感谢所有对此问题感兴趣的人。
std::vector<std::vector<int>> Combinations::combs(int n, int r) {
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
std::vector<std::vector<int>> sol;
do {
std::vector<int> row;
for (int i = 0; i < n; ++i) {
if (v[i]) {
row.push_back(i+1);
}
}
sol.push_back(row);
} while (std::next_permutation(v.begin(), v.end()));
return sol;
}
【问题讨论】: