我想有效地生成的基于数字的开始列表上的数字的组合的唯一列表。
I would like to efficiently generate a unique list of combinations of numbers based on a starting list of numbers.
例如启动列表= [1,2,3,4,5],但该算法应适用于[1,2,3 ... N]
example start list = [1,2,3,4,5] but the algorithm should work for [1,2,3...n]
结果=
[1],[2],[3],[4],[5] [1,2],[1,3],[1,4],[1,5] [1,2,3],[1,2,4],[1,2,5] [1,3,4],[1,3,5],[1,4,5] [2,3],[2,4],[2,5] [2,3,4],[2,3,5] [3,4],[3,5] [3,4,5] [4,5]
[1],[2],[3],[4],[5] [1,2],[1,3],[1,4],[1,5] [1,2,3],[1,2,4],[1,2,5] [1,3,4],[1,3,5],[1,4,5] [2,3],[2,4],[2,5] [2,3,4],[2,3,5] [3,4],[3,5] [3,4,5] [4,5]
请注意。我不想重复的组合,虽然我可以和他们住在一起,例如,在上面的例子中,我并不真正需要的组合[1,3,2],因为它已经present为[1,2,3]
Note. I don't want duplicate combinations, although I could live with them, eg in the above example I don't really need the combination [1,3,2] because it already present as [1,2,3]
没有为你问一个名称。这就是所谓的电源设置。
There is a name for what you're asking. It's called the power set.
谷歌搜索权力集法使我这个递归解决方案。
Googling for "power set algorithm" led me to this recursive solution.
有关的仇敌:
def powerset(set)
return [set] if set.empty?
p = set.pop
subset = powerset(set)
subset | subset.map { |x| x | [p] }
end