Posted: 29 Sep, 2020
Given a number 'N', you need to find all possible unique ways to represent this number as the sum of positive integers.
1. By unique it is meant that no other composition can be expressed as a permutation of the generated composition. For eg. [1, 2, 1] and [1, 1, 2] are not unique. 2. You need to print all combinations in non-decreasing order for eg. [1, 2, 1] or [1, 1, 2] will be printed as [1, 1, 2], however, the order of printing all the sequences can be random.
The first and the only line of the input contains an integer 'N' representing the given number.
Each line of the output contains one unique sequence which sums up to 'N'. There will be 'K' lines of output containing one unique sequence on each line in non-decreasing order which sums up to 'N'. 'K' is the total number of unique sequences.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= N <= 50 Time Limit: 1sec
- The Naive approach uses a brute-force method to generate all the possible compositions possible by partitioning the given number
- For generating the combinations, let’s start from 1 because the minimum positive integer is 1. For every position, we will try all numbers from 1 to N, and solve the problem recursively for other positions.
- When we place a number at a position we decrease the remaining sum and move to the next position.
- Whenever our remaining sum = 0, we will store the sequence in an array, sort that array(to store sequence in nondecreasing order), and insert it into a set.
- We need to store each valid combination in a set so that we can avoid the duplicate combinations in our final answer [For example, the sequence [1,2,3] and [3,1,2] are the same, so we need to sort both sequences so that they both become [1,2,3] and the set will store only one instance of [1,2,3]. ]
- In the end, we will print all possible combinations.