Generate all unique partitions of an integer | Set 2 - GeeksforGeeks

09 Dec, 2021
Given a positive integer n, the task is to generate all possible unique ways to represent n as sum of positive integers.Examples: 
Input: 4 Output: 4 3 1 2 2 2 1 1 1 1 1 1Input: 3 Output: 3 2 1 1 1 1  
Approach: We have already discussed the implementation of generating unique partitions in this post. This post contains another and far more intuitive implementation for the above problem using recursion.The idea is simple and is kind of same approach as used here. We have to move recursively from n to 1 and keep on appending the numbers used to form sum in the array. When the sum becomes equal to n then we print the array and return. The base cases considered in the implementation are: remSum == 0: Required n is formed so print the array.Then we have started forming required sum using the max value number used in the previous partition. If that number becomes greater than n we ignore it else we append that number to the array and move recursively to next iteration to form sum = (remSum – i) and where max value number that could be used is i or less than i. This way we can generate the required unique partitions.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Array to store the numbers used// to form the required sumint dp[200];int count = 0; // Function to print the array which contains// the unique partitions which are used// to form the required sumvoid print(int idx){    for (int i = 1; i < idx; i++) {        cout << dp[i] << " ";    }    cout << endl;} // Function to find all the unique partitions// remSum = remaining sum to form// maxVal is the maximum number that// can be used to make the partitionvoid solve(int remSum, int maxVal, int idx, int& count){     // If remSum == 0 that means the sum    // is achieved so print the array    if (remSum == 0) {        print(idx);        count++;        return;    }     // i will begin from maxVal which is the    // maximum value which can be used to form the sum    for (int i = maxVal; i >= 1; i--) {        if (i > remSum) {            continue;        }        else if (i <= remSum) {             // Store the number used in forming            // sum gradually in the array            dp[idx] = i;             // Since i used the rest of partition            // cant have any number greater than i            // hence second parameter is i            solve(remSum - i, i, idx + 1, count);        }    }} // Driver codeint main(){    int n = 4, count = 0;     solve(n, n, 1, count);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{     // Array to store the numbers used    // to form the required sum    static int[] dp = new int[200];    static int count = 0;     // Function to print the array which contains    // the unique partitions which are used    // to form the required sum    static void print(int idx)    {        for (int i = 1; i < idx; i++)        {            System.out.print(dp[i] + " ");        }        System.out.println("");    }     // Function to find all the unique partitions    // remSum = remaining sum to form    // maxVal is the maximum number that    // can be used to make the partition    static void solve(int remSum, int maxVal,                        int idx, int count)    {         // If remSum == 0 that means the sum        // is achieved so print the array        if (remSum == 0)        {            print(idx);            count++;            return;        }         // i will begin from maxVal which is the        // maximum value which can be used to form the sum        for (int i = maxVal; i >= 1; i--)        {            if (i > remSum)            {                continue;            }            else if (i <= remSum)            {                 // Store the number used in forming                // sum gradually in the array                dp[idx] = i;                 // Since i used the rest of partition                // cant have any number greater than i                // hence second parameter is i                solve(remSum - i, i, idx + 1, count);            }        }    }     // Driver code    public static void main(String[] args)    {        int n = 4, count = 0;         solve(n, n, 1, count);    }} // This code has been contributed by 29AjayKumar
# Python 3 implementation of the approach # Array to store the numbers used# to form the required sumdp = [0 for i in range(200)]count = 0 # Function to print the array which contains# the unique partitions which are used# to form the required sumdef print1(idx):    for i in range(1,idx,1):        print(dp[i],end = " ")    print("\n",end = "") # Function to find all the unique partitions# remSum = remaining sum to form# maxVal is the maximum number that# can be used to make the partitiondef solve(remSum,maxVal,idx,count):    # If remSum == 0 that means the sum    # is achieved so print the array    if (remSum == 0):        print1(idx)        count += 1        return    # i will begin from maxVal which is the    # maximum value which can be used to form the sum    i = maxVal    while(i >= 1):        if (i > remSum):            i -= 1            continue        elif (i <= remSum):            # Store the number used in forming            # sum gradually in the array            dp[idx] = i             # Since i used the rest of partition            # cant have any number greater than i            # hence second parameter is i            solve(remSum - i, i, idx + 1, count)            i -= 1 # Driver codeif __name__ == '__main__':    n = 4    count = 0     solve(n, n, 1, count)     # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{     // Array to store the numbers used    // to form the required sum    static int[] dp = new int[200];     // Function to print the array which contains    // the unique partitions which are used    // to form the required sum    static void print(int idx)    {        for (int i = 1; i < idx; i++)        {            Console.Write(dp[i] + " ");        }        Console.WriteLine("");    }     // Function to find all the unique partitions    // remSum = remaining sum to form    // maxVal is the maximum number that    // can be used to make the partition    static void solve(int remSum, int maxVal,                        int idx, int count)    {         // If remSum == 0 that means the sum        // is achieved so print the array        if (remSum == 0)        {            print(idx);            count++;            return;        }         // i will begin from maxVal which is the        // maximum value which can be used to form the sum        for (int i = maxVal; i >= 1; i--)        {            if (i > remSum)            {                continue;            }            else if (i <= remSum)            {                 // Store the number used in forming                // sum gradually in the array                dp[idx] = i;                 // Since i used the rest of partition                // cant have any number greater than i                // hence second parameter is i                solve(remSum - i, i, idx + 1, count);            }        }    }     // Driver code    public static void Main()    {        int n = 4, count = 0;         solve(n, n, 1, count);    }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the approach // Array to store the numbers used// to form the required sumvar dp = Array.from({length: 200}, (_, i) => 0);var count = 0; // Function to print the array which contains// the unique partitions which are used// to form the required sumfunction print(idx){    for (var i = 1; i < idx; i++)    {        document.write(dp[i] + " ");    }    document.write('<br>');} // Function to find all the unique partitions// remSum = remaining sum to form// maxVal is the maximum number that// can be used to make the partitionfunction solve(remSum , maxVal,idx , count){     // If remSum == 0 that means the sum    // is achieved so print the array    if (remSum == 0)    {        print(idx);        count++;        return;    }     // i will begin from maxVal which is the    // maximum value which can be used to form the sum    for (var i = maxVal; i >= 1; i--)    {        if (i > remSum)        {            continue;        }        else if (i <= remSum)        {             // Store the number used in forming            // sum gradually in the array            dp[idx] = i;             // Since i used the rest of partition            // cant have any number greater than i            // hence second parameter is i            solve(remSum - i, i, idx + 1, count);        }    }} // Driver codevar n = 4, count = 0; solve(n, n, 1, count); // This code contributed by Princi Singh </script>
4 
3 1 
2 2 
2 1 1 
1 1 1 1
 
SURENDRA_GANGWAR
29AjayKumar
ankthon
princi singh
simranarora5sos
Numbers
Dynamic Programming
Recursion
Dynamic Programming
Recursion
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Write a program to print all permutations of a given string
Recursion
Print all possible combinations of r elements in a given array of size n
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Sum of the digits of a given number