Get all possible subsets - preserving order

时光总嘲笑我的痴心妄想 提交于 2019-12-04 17:47:39
Niklas B.

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.

If I understand it correctly, you want to insert "delimiters" into a list, to partition it. Taking your example, and using the | character to indicate the delimiter,

1 2 3
1 2|3
1|2 3
1|2|3

are the solutions you want.

In a list (I'm calling it a list and not a set because you need the order preserved) of n elements, there are n-1 potential positions for a delimiter. In the example above, there are two positions. In each position, a delimiter might or might not be present.

You can use the binary representation of numbers from 0 to 2^(n-1) - 1 to list all possible arrangements of delimiters. In your example, this'll be number from 0..3.

0:  00
1:  01
2:  10
3:  11
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!