我刚刚接受了一些采访递归问题,其中一个是打印出一组的一个子集。这是我在ruby中的代码
def subset(arr, ifTrue, element, size)
if element == 0
ifTrue[element] = true
print "{ "
ifTrue.each_with_index { |item, index| print arr[index] if item === true }
print " }\n"
ifTrue[element] = false
print "{ "
ifTrue.each_with_index { |item, index| print arr[index] if item === true }
print " }\n"
else
ifTrue[element] = false
subset(arr, ifTrue, element - 1, size)
ifTrue[element] = true
subset(arr, ifTrue, element - 1, size)
end
end
arr = ['A','B','C']
ifTrue = Array.new(arr.size,false)
subset(arr, ifTrue, 2, arr.size)
输出正确
{ A }
{ }
{ AB }
{ B }
{ AC }
{ C }
{ ABC }
{ BC }
但我想知道如何修改它,以便以更好的顺序打印它,例如
{ }
{ A }
{ B }
{ C }
{ AB }
{ AC }
{ BC }
{ ABC }
没有队列/排序
答案 0 :(得分:1)
你也应该递归地建立一组子集,这样你就可以按照自己的意愿对它进行排序:
def subset(arr, ifTrue, element, size, subsets)
if element == 0
ifTrue[element] = true
ss = []
ifTrue.each_with_index { |item, index| ss << arr[index] if item === true }
subsets << ss
ss = []
ifTrue[element] = false
ifTrue.each_with_index { |item, index| ss << arr[index] if item === true }
subsets << ss
else
ifTrue[element] = false
subset(arr, ifTrue, element - 1, size, subsets)
ifTrue[element] = true
subset(arr, ifTrue, element - 1, size, subsets)
end
end
arr = ['A','B','C']
ifTrue = Array.new(arr.size,false)
subsets = []
subset(arr, ifTrue, 2, arr.size, subsets)
puts (subsets.sort { |x,y| x.count <=> y.count }).to_s
输出:
$ ruby subset.rb
# [[], ["A"], ["B"], ["C"], ["A", "B"], ["A", "C"], ["B", "C"], ["A", "B", "C"]]
修改强>
要完全按照您的意愿输出文本,请使用以下内容替换调用puts
的最后一行:
subsets = subsets.sort { |x,y| x.count <=> y.count }
subsets.each do |subset|
str = "{ "
subset.each { |x| str << x }
str << " }"
puts str
end
这是输出:
$ ruby subset.rb
{ }
{ A }
{ B }
{ C }
{ AB }
{ AC }
{ BC }
{ ABC }