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 given partition should be equal to the given number. For example, for input n = 6
, all possible partitions having 2 or more elements with distinct elements are:
- 1, 5
- 1, 2, 3
- 2, 4
I think a recursive approach should work, but I am unable to take care of the added constraint of distinct elements. A pseudo code or a sample code in C/C++/Java would be greatly appreciated.
Thanks!
Edit: If it makes things easier, I can ignore the restriction of the partitions having atleast 2 elements. This will allow the number itself to be added to the list (eg, 6 itself will be a trivial but valid partition).
I sketched this solution (it can be beautified and optimized) that shouldn't generate duplicates:
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:
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:
What you're trying to do doesn't make a lot of sense to me but here's how I would approach it.
First, I'd create a loop that iterates
i
from 1 ton
- 1. In the first loop, you could add the partition 1, i. Then I'd go recursive using the value ini
to get all the sub-partitions that can also be added to 1.And then continue to 2, and so on.
You don't need recursion at all. The list of numbers is essentially a stack, and by iterating in order you ensure no duplicates.
Here's a version which shows what I mean (you tagged this C, so I wrote it in C. In C++ you could use a dynamic container with push and pop, and tidy this up considerably).