假设我的数组的长度是5,即a5和其中的一些随机值{11,32,53,22,67}这里可能的组合总数是120(5*4*3*2*1),我该如何计算所有可能的值并将其存储
我也查过geeksforgeek和stackoverflow上的一些代码,但我找不到解决方案。
vector<int> people;
vector<int> combination;
void pretty_print(const vector<int>& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void go(int offset, int k) {
if (k == 0) {
pretty_print(combination);
return;
}
for (int i = offset; i <= people.size() - k; ++i) {
combination.push_back(people[i]);
go(i+1, k-1);
combination.pop_back();
}
}
int main() {
int n = 5, k = 3;
for (int i = 0; i < n; ++i) { people.push_back(i+1); }
go(0, k);
return 0;
}
上面的代码片段是在网上找到的,它在一定程度上帮助我找到了3个数字的组合。提前感谢您的帮助
发布于 2019-10-05 17:46:06
您可以使用此解决方案。https://notepad.pw/42f0zx9r。只需添加一个计数器即可获得您想要的解决方案。
https://stackoverflow.com/questions/58246833
复制相似问题