向量值的不同组合 [英] the different combinations of a vector's values

查看:119
本文介绍了向量值的不同组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个n个值的向量,我想获取其值的不同组合,例如:如果我有vect = [a,b,c],我想要的不同组合是:[a,b ,c],[a,b],[a,c],[b,c],[a],[b],[c]

Suppose I have a vector of n values, I want to get the different combinations of its values, for example: if I have vect = [a, b, c] the different combinations that I want are: [a, b, c], [a,b], [a,c], [b,c], [a], [b], [c]

请注意,例如[a,b]与[b,a]相同,因此我不需要同时保留它们.

Note that for example [a,b] is the same as [b,a] so I don't need to keep both of them.

推荐答案

02^vector.size() - 1的计数.如果您的循环变量的第i位为1,则在您的组合中添加vector[i].

Count from 0 to 2^vector.size() - 1. If bit i of your loop variable is 1, include vector[i] in your combination.

vector<char> v;
v.push_back('a');
v.push_back('b');
v.push_back('c');
for (int counter = 0; counter < (1 << v.size()); ++counter)
{
    vector<char> combination;
    for (int i = 0; i < v.size(); ++i)
    {
        if (counter & (1 << i))
            combination.push_back(v[i]);
    }

    // do something with combination
}

如果要排除空集,请从1开始计数.

if you want to exclude the empty set, start counting at 1.

这篇关于向量值的不同组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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