开发者

How to generate a subset of a given array in C++? [closed]

开发者 https://www.devze.com 2023-04-12 21:17 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years a开发者_如何学JAVAgo.

I want to generate a subsets of size n = 0, 1, 2, ... of a set of numbers.

There should not be repetition of the same numbers with different order, like 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号