在n成员数组中产生m成员组合 [英] producing m-member combination in a n-member array

查看:91
本文介绍了在n成员数组中产生m成员组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含n个成员的数组.我还有另一个数字:m,(m <= n),由用户输入.现在,我想在数组中生成所有可能的"m"个成员组合.

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

现在,我想要显示这10种组合的代码.

Now I want a code for showing these 10 combination.like:

{{a,b,c},{a,b,d},{a,b,e},.....}

排列中的项目顺序很重要.例如,{a,b,d}是正确的,但{b,d,a}是错误的.排列项应按它们在矩阵中的顺序排列.

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

推荐答案

组合:

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()));
}

实时演示

这篇关于在n成员数组中产生m成员组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆