问题
I have an array with n members. And I have another number: m,(m <= n) which is entered by user. Now I want to produce all of possible "m" member combination in the array.
A[5] = {a,b,c,d,e};
B = 3
Number of combination: C(5, 3) = 10
Now I want a code for showing these 10 combination.like:
{{a,b,c},{a,b,d},{a,b,e},.....}
Order of items in permutation is important. For example {a,b,d} is right but {b,d,a} is wrong. The permutation items should come in their order in our matrix.
I appropriate any help from your side. Thanks in advance
回答1:
For combination:
template <typename T>
void Combination(const std::vector<T>& v, std::size_t count)
{
assert(count <= v.size());
std::vector<bool> bitset(v.size() - count, 0);
bitset.resize(v.size(), 1);
do {
for (std::size_t i = 0; i != v.size(); ++i) {
if (bitset[i]) {
std::cout << v[i] << " ";
}
}
std::cout << std::endl;
} while (std::next_permutation(bitset.begin(), bitset.end()));
}
Live demo
来源:https://stackoverflow.com/questions/34394366/producing-m-member-combination-in-a-n-member-array