Find all combinations of a given set of integers summing up to a given sum

前端 未结 3 2004
面向向阳花
面向向阳花 2021-01-07 14:00

I am looking for an answer to the following problem.

Given a set of integers (no duplicates) and a sum, find all possible combinations of the set\'s elements summing

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-07 14:36

    Here is a Haskell function that calculates the answer:

    partitions 0 xs = [[]]
    partitions _ [] = []
    partitions n (xxs@(x:xs)) | n < 0 = []
                              | otherwise = (map (x:) (partitions (n-x) xxs)) ++ partitions n xs
    

    Examples:

    *Main>  partitions 1 [1]
    [[1]]
    *Main>  partitions 5 [1..5]
    [[1,1,1,1,1],[1,1,1,2],[1,1,3],[1,2,2],[1,4],[2,3],[5]]
    *Main> length $ partitions 10 [1..10]
    42
    *Main> length $ partitions 20 [1..20]
    627
    *Main> length $ partitions 40 [1..40]
    37338
    *Main> partitions 10 [1,2,4]
    [[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,2],[1,1,1,1,1,1,2,2],[1,1,1,1,1,1,4],[1,1,1,1,2,2,2],[1,1,1,1,2,4],[1,1,2,2,2,2],[1,1,2,2,4],[1,1,4,4],[2,2,2,2,2],[2,2,2,4],[2,4,4]]
    

    Semi-live demo

提交回复
热议问题