首页 > 代码库 > 全组合的递归实现(ruby)

全组合的递归实现(ruby)

着急用所以直接扒了一个C++算法翻译成了ruby…暂记

 1 nodes = ["node1", "node2", "node3", "node4", "node5", "node6"]
 2 
 3 def combine_array(arr, start, index, count, num ,len, output)         
 4     for i in (start..len-1)
 5       index[count-1] = i
 6       if count-1 == 0 then
 7         out = []
 8         for j in (0..num-1)       
 9         out << arr[index[j]]                     
10         end
11         #puts "#{out}"
12         #puts "------------"
13         output << out
14       else
15         combine_array(arr, i+1, index, count-1, num, len, output)
16       end
17    end
18 end
19 
20 for i in (1..6)
21   outs = []
22   combine_array(nodes, 0, index, i, i, len, outs)
23   p outs
24   puts "------------"
25 end

 

全组合的递归实现(ruby)