C++使用string和prev_permutation快速得到组合数C_n^k的所有可能结果
作者:
Julius_6
,
2024-10-24 02:25:59
,
所有人可见
,
阅读 1
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printCombination(const vector<int>& vec, const string& bitmask) {
vector<int> combination;
for (int i = 0; i < vec.size(); ++i) {
if (bitmask[i] == '1') {
combination.push_back(vec[i]);
}
}
for (int num : combination) {
cout << num << " ";
}
cout << "\n";
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6};
int n = vec.size();
int k = 3;
string bitmask;
// The initial bitmask of k 1's followed by (n-k) 0's
for (int i = 0; i < n; ++i) {
if(i < k) bitmask += '1';
else bitmask += '0';
}
do {
printCombination(vec, bitmask);
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
return 0;
}