I was solving a programming exercise and came across a problem over which I am not able to satisfactorily find a solution. The problem goes as follows:
Print all unique integer partitions given an integer as input.
Integer partition is a way of writing n as a sum of positive integers.
for ex: Input=4 then output should be Output=
1 1 1 1
1 1 2
2 2
1 3
4
How should I think about solving this problem? I was wondering about using recursion. Can anyone provide me an algorithm for this question? Or a hint towards solution. any explanation for such kind of problems is welcome. (I am a beginner in programming world) Thank you!!
I would approach it this way:
First, generalize the problem. You can define a function
with the specification:
Note that there is always at least 1 solution (provided both target and maxValue are positive), which is all 1s.
You can use this method recursively. So lets first think about the base case:
should simply print
suffix
.If
target
is not0
, you have to options: either usemaxValue
or not (ifmaxValue > target
there is only one option: don't use it). If you don't use it, you should lowermaxValue
by1
.That is:
Combining this all leads to a relatively simple method (coded in Java here and I reordered the statements a little to obtain the very same order as you described):
You can simply call this as
which outputs
You can also choose to first create a list of all solutions and only print afterwards, like this: