如何在 C++ 中生成给定数组的子集?
我想生成一组数字的大小为 n = 0, 1, 2, ...
的子集。
不应该以不同的顺序重复相同的数字,例如 2-3-4 = 3-2-4 = 4-2-3 = 4-3-2
例如
vector<unsigned int> list = {2,4,6,8,9}
,子集就像,
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}
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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
生成长度等于您的数字数量的所有二进制数。
接下来根据位置选择数字并将它们映射到相应的集合(即,如果 001,您将其映射到 1,对于 101,您将其映射到 3)。
对于初始组 {1,2,3}:
我只是给您一个想法,因为这看起来像家庭作业,而这不是一个家庭作业解决网站。这应该给你一个起点。
Generate all binary numbers of length equal to your number of numbers.
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}:
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.
大多数算法的工作原理是生成所有可能的子集,然后获取您想要的子集[这里是其长度]。
您可以使用的想法之一是递归。抽象所以你做你的作业。
考虑给定的集合
G = {1,2,3}
,您必须为其找到子集。维护一个集合
Y = { {} }
以 开头。第 1 步:1 可能存在,也可能不存在。 Y = { {1} , {} } 。 G = {2,3}
第 2 步:2 可能存在,也可能不存在。 Y = { {1,2} , {2} , {1} , {} } 。 G = {3} .
Ans 直到
G != {}
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
You can use recurisve-backtracking to solve this.