Generating all distinct partitions of a number

后端 未结 5 1922
北海茫月
北海茫月 2020-12-14 12:56

I am trying to write a C code to generate all possible partitions (into 2 or more parts) with distinct elements of a given number. The sum of all the numbers of a g

5条回答
  •  盖世英雄少女心
    2020-12-14 13:46

    First, write a recursive algorithm that returns all partitions, including those that contain repeats.

    Second, write an algorithm that eliminates partitions that contain duplicate elements.

    EDIT:

    You can avoid results with duplicates by avoiding making recursive calls for already-seen numbers. Pseudocode:

    Partitions(n, alreadySeen)
     1. if n = 0 then return {[]}
     2. else then
     3.    results = {}
     4.    for i = 1 to n do
     5.       if i in alreadySeen then continue
     6.       else then
     7.          subresults = Partitions(n - i, alreadySeen UNION {i})
     8.          for subresult in subresults do
     9.             results = results UNION {[i] APPEND subresult}
    10.    return results
    

    EDIT:

    You can also avoid generating the same result more than once. Do this by modifying the range of the loop, so that you only add new elements in a monotonically increasing fashion:

    Partitions(n, mustBeGreaterThan)
    1. if n = 0 then return {[]}
    2. else then
    3.    results = {}
    4.    for i = (mustBeGreaterThan + 1) to n do
    5.       subresults = Partitions(n - i, i)
    6.       for subresult in subresults do
    7.          results = results UNION {[i] APPEND subresult}
    8.    return results
    

提交回复
热议问题