1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

组合生成

Posted on 2013-03-03 16:11  1957  阅读(151)  评论(0编辑  收藏  举报

就是每个元素取还是不取!

 

combinations :: Int -> [a] -> [[a]]
combinations _ [] = [[]]
combinations 0 _  = [[]]
combinations k (x:xs) = x_start ++ others
   where
       x_start = [x:rest | rest <- combinations (k - 1) xs]
       others = if k <= length xs then combinations k xs else []

*Main> combinations 3 "abcedfg"
["abc","abe","abd","abf","abg","ace","acd","acf","acg","aed","aef","aeg","adf","
adg","afg","bce","bcd","bcf","bcg","bed","bef","beg","bdf","bdg","bfg","ced","ce
f","ceg","cdf","cdg","cfg","edf","edg","efg","dfg"]