从数字列表中获取所有可能的组合
我正在寻找一种有效的方法来实现此目的:
您有一个数字列表 1.....n (通常:1..5 或 1..7 左右 - 相当小,但可能会有所不同视情况而定)
您需要这些数字的所有长度的所有组合,例如,只有一个数字的所有组合({1},{2},... {n}),然后是两个不同数字的所有组合({1,2}, {1,3}, {1,4} ..... {n-1, n} ),则其中三个数字的所有组合 ({1,2,3}, {1,2,4})等等
基本上,在组内,顺序是无关的,因此 {1,2,3} 相当于 {1,3,2} - 这只是获取 x 的所有组的问题该列表中的数字
似乎应该有一个简单的算法 - 但到目前为止我的搜索是徒劳的。大多数组合和排列算法似乎 a) 考虑顺序(例如 123 不等于 132),并且它们似乎总是对单个字符或数字字符串进行操作......
任何人都有一个伟大的,nice'n'他们的快速算法?
谢谢!
I'm looking for an efficient way to achieve this:
you have a list of numbers 1.....n (typically: 1..5 or 1..7 or so - reasonably small, but can vary from case to case)
you need all combinations of all lengths for those numbers, e.g. all combinations of just one number ({1}, {2}, .... {n}), then all combinations of two distinct numbers ({1,2}, {1,3}, {1,4} ..... {n-1, n} ), then all combinations fo three of those numbers ({1,2,3}, {1,2,4}) and so forth
Basically, within the group, the order is irrelevant, so {1,2,3} is equivalent to {1,3,2} - it's just a matter of getting all groups of x numbers from that list
Seems like there ought to be a simple algorithm for this - but I have searched in vain so far. Most combinatorics and permutation algorithms seems to a) take order into account (e.g. 123 is not equal to 132), and they always seems to operate on a single string of characters or numbers....
Anyone have a great, nice'n'quick algorithm up their sleeve??
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是我的代码,但您正在寻找电源集。谷歌给了我这个解决方案,这似乎不起作用:
来源:http://rosettacode.org/wiki/ Power_set#C.23
Not my code, but you're looking for the powerset. Google gave me this solution, which seems t work:
Source: http://rosettacode.org/wiki/Power_set#C.23
只需增加一个二进制数并获取与所设置的位相对应的元素即可。
例如,
00101101
表示获取索引 0、2、3 和 5 处的元素。由于您的列表只是 1..n,因此该元素只是索引 + 1。这将生成- 顺序排列。换句话说,只会生成
{1, 2, 3}
。不是{1, 3, 2}
或{2, 1, 3}
或{2, 3, 1}
等。Just increment a binary number and take the elements corresponding to bits that are set.
For instance,
00101101
would mean take the elements at indexes 0, 2, 3, and 5. Since your list is simply 1..n, the element is simply the index + 1.This will generate in-order permutations. In other words, only
{1, 2, 3}
will be generated. Not{1, 3, 2}
or{2, 1, 3}
or{2, 3, 1}
, etc.这是我过去为了完成这样的任务而写的东西。
它是通用的,因此适用于整数、长整型、字符串、Foos 等。
This is something I have written in the past to accomplish such a task.
It's generic, so it will work for ints, longs, strings, Foos, etc.