简体   繁体   English

集合中所有可能的组合

[英]All possible combinations from sets

I have a set of numbers: 我有一组数字:

1,22
1,46
32,1
1,9
32,22
1,14
1,45
1,33
33,22
45,22
32,46
32,9
3,1
3,9
3,22
3,32
3,46
9,22
46,22
46,45
46,33
15,1
15,46
15,6
15,22
15,3
15,9
15,45
15,33
15,32
15,14

I need to get combinations from them with a rule that each new pair can only be appended if the latter number is the same as the first in the pair. 我需要从他们那里得到一个规则,即每个新对只能在后一个数字与该对中的第一个相同时才能追加。

For example if I have a pair {15,1}, the next on can be only {1,46} and the next {46,45}, and the final pair must end with the first number of the whole set. 例如,如果我有一对{15,1},则下一个on只能是{1,46},下一个{46,45},最后一对必须以整个集合的第一个数字结尾。 In this case it could be for example {45,1}. 在这种情况下,它可能是{45,1}。

So the end result of sets with 4 set limit would be 因此,具有4个集合限制的集合的最终结果将是

{15,1,1,46,46,45,45,1}

I can do basic power sets and generate all possible combinations from set of numbers but this seems to be too advanced for me. 我可以进行基本的幂集运算并从一组数字生成所有可能的组合,但这对我来说似乎太高级了。

I can do C, Javascript or PHP so all the help or solutions to this are highly appreciated. 我可以使用C,Javascript或PHP,因此非常感谢您提供的所有帮助或解决方案。 And for clarification, this is not a homework, this is just something I would like to learn and understand. 为了澄清起见,这不是家庭作业,这只是我想学习和理解的东西。

This looks as if some graph data structure, and some graph algorithms, would be appropriate. 看起来某些图形数据结构和某些图形算法似乎是合适的。 Your graph would comprise nodes (each of which is a number) and edges (each of which represents one of your pairs). 您的图形将包括节点(每个节点都是一个数字)和边(每个节点代表一对)。 Then write the appropriate routine for walking round the graph. 然后编写适当的例程来遍历图。 It's not entirely clear from your question what the rules for the walk are, but I guess you know. 从您的问题中尚不能完全清楚步行的规则是什么,但我想您知道。

EDIT 编辑

Of course, I should point out that what you have is already a graph data structure, it's called an adjacency list . 当然,我应该指出,您所拥有的已经是一个图形数据结构,称为邻接表 Google around for algorithms and representations. 谷歌周围的算法和表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM