How to generate a subset of a given array in C++? [closed]
I want to generate a subsets of size n = 0, 1, 2, ...
of a set of numbers.
2-3-4 = 3-2-4 = 4-2-3 = 4-3-2
e.g.
vector<unsigned int> list = {2,4,6,8,9}
so subsets will be like,
n=0 {}
n=1 {2}{4}{6}{8}{9}
n=2 {2,4}{2,6}{2,8}{2,9}{4,6}{4,8}{4,9}{6,8}{6,9}{8,9}
Generate all binary numbers of length equal to your number of numbers.
3 numbers:
000
001
010
011
100
101
110
111
Next choose the numbers according to position and map them to the according set (i.e. if 001, you would map it to 1, for 101 you would map it to 3).
For initial set {1,2,3}:
{} ->0
{3} ->1
{2} ->1
{2,3} ->2
{1} ->1
{1,3} ->2
{1,2} ->2
{1,2,3} ->3
I'm just giving you an idea because this seems like homework and this isn't a homework solving site. This should give you a starting point.
Most algorithms work by generating all possible subsets and then take the ones you want [ here its length ].
One of the ideas you can use is recursion . Abstracted so you do your homework .
Consider a given set G = {1,2,3}
for which you have to find subsets .
Maintain a set Y = { {} }
to start with .
Step 1 : 1 may or may not be there . Y = { {1} , {} } . G = {2,3}
Step 2 : 2 may or may not be there . Y = { {1,2} , {2} , {1} , {} } . G = {3} .
Ans it goes till G != {}
For the subsets, the rule is
"There are at least two subsets: null and the set itself. All subsets count is always = 2^(n), which n is the number of elements in the set."
You can use recurisve-backtracking to solve this.
精彩评论