获取所有可能的子集 - preserving订单 [英] Get all possible subsets - preserving order
问题描述
这是一个跟进这个问题: <一href="http://stackoverflow.com/questions/8643812/generate-all-unique-subsets-of-a-set-not-a-powerset/8644157#comment12370703_8644157">Generate所有&QUOT;独特的&QUOT;一组(而不是幂)
的子集我的问题是一样的,但我觉得可能是一个更优化的解决方案时,为了在新的子集和整个子集的项目必须是preserved。
例如:
[1,2,3]
将导致:
[1],[2],[3]
[[1,2],[3]]
[1],[2,3]]
[[1,2,3]]
我已经回答了这个问题为Python ,所以我很快就移植我的解决方案转移到红宝石:
高清spannings(LST)
返回enum_for(:spannings,LST),除非block_given?
产量[LST]
(1 ... lst.size)。每个做|我|
spannings(LST [我..- 1])办|休息|
产生[LST [0,1]] +休息
结束
结束
结束
p spannings([1,2,3,4])。to_a
请参阅我的其他答案的完整说明,如何以及为什么这个工程。
This is a follow up to this question: Generate all "unique" subsets of a set (not a powerset)
My problem is the same, but I think there might be a more optimized solution when order of items in the new subsets and across the subsets needs to be preserved.
Example:
[1, 2, 3]
Would result in:
[[1], [2], [3]]
[[1, 2], [3]]
[[1], [2, 3]]
[[1, 2, 3]]
I've already answered this question for Python, so I quickly ported my solution over to Ruby:
def spannings(lst)
return enum_for(:spannings, lst) unless block_given?
yield [lst]
(1...lst.size).each do |i|
spannings(lst[i..-1]) do |rest|
yield [lst[0,i]] + rest
end
end
end
p spannings([1,2,3,4]).to_a
See my other answer for a complete explanation of how and why this works.
这篇关于获取所有可能的子集 - preserving订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!