How do i generate all possible subsets of an binary string?

后端 未结 5 1948
隐瞒了意图╮
隐瞒了意图╮ 2021-01-20 22:06

i have a problem, that i don\'t know how to solve it.

i have a binary string and i want to generate all possible binary substrings.

Example :



        
5条回答
  •  温柔的废话
    2021-01-20 22:40

    This does it:

    vector submasks(string in)
    {
        vector out;
    
        out.push_back(string(in.size(), '0'));
    
        for (int i = 0; i < in.size(); ++i)
        {
            if (in[i] == '0') continue;
    
            int n = out.size();
            for (int j = 0; j < n; ++j)
            {
                string s = out[j];
                s[i] = '1';
                out.push_back(s);
            }
        }
    
        return out;
    }
    

    The algorithm does this:

    1. Start with a vector containing just an empty bit-string '00000...'
    2. For each 1 in the input string: create a copy of each string in the output vector with that 1 set.

    I think that's pretty much optimal.

提交回复
热议问题