Generate all unique partitions of an integer

Given a positive integer n, generate all possible unique ways to represent n as sum of positive integers.
Examples:

  Input: n = 2
  Output: 
  2
  1 1

  Input: n = 3
  Output: 
  3
  2 1
  1 1 1
  Note: 2+1 and 1+2 are considered as duplicates.

  Input: n = 4
  Output: 
  4
  3 1
  2 2
  2 1 1
  1 1 1 1 

Solution: We print all partition in sorted order and numbers within a partition are also printed in sorted order (as shown in the above examples). The idea is to get next partition using the values in current partition. We store every partition in an array p[]. We initialize p[] as n where n is the input number. In every iteration. we first print p[] and then update p[] to store the next partition. So the main problem is to get next partition from a given partition.

Steps to get next partition from current partition:
We are given current partition in p[] and its size. We need to update p[] to store next partition. Values in p[] must be sorted in non-increasing order.

  1. Find the rightmost non-one value in p[] and store the count of 1’s encountered before a non-one value in a variable rem_val (It indicates sum of values on right side to be updated). Let the index of non-one value be k.
  2. Decrease the value of p[k] by 1 and increase rem_val by 1. Now there may be two cases:

    • a) If p[k] is more than or equal to rem_val. This is a simple case (we have the sorted order in new partition). Put rem_val at p[k+1] and p[0…k+1] is our new partition.
    • b) Else (This is a interesting case, take initial p[] as {3, 1, 1, 1}, p[k] is decreased from 3 to 2, rem_val is increased from 3 to 4, the next partition should be {2, 2, 2}).
  3. Copy p[k] to next position, increment k and reduce count by p[k] while p[k] is less than rem_val. Finally, put rem_val at p[k+1] and p[0…k+1] is our new partition. This step is like dividing rem_val in terms of p[k] (4 is divided in 2’s).

Following is the implementation of above algorithm:

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to generate all unique
// partitions of an integer
#include<iostream>
using namespace std;
  
// A utility function to print an array p[] of size 'n'
void printArray(int p[], int n)
{
    for (int i = 0; i < n; i++)
       cout << p[i] << " ";
    cout << endl;
}
  
void printAllUniqueParts(int n)
{
    int p[n]; // An array to store a partition
    int k = 0;  // Index of last element in a partition
    p[k] = n;  // Initialize first partition as number itself
  
    // This loop first prints current partition, then generates next
    // partition. The loop stops when the current partition has all 1s
    while (true)
    {
        // print current partition
        printArray(p, k+1);
  
        // Generate next partition
  
        // Find the rightmost non-one value in p[]. Also, update the
        // rem_val so that we know how much value can be accommodated
        int rem_val = 0;
        while (k >= 0 && p[k] == 1)
        {
            rem_val += p[k];
            k--;
        }
  
        // if k < 0, all the values are 1 so there are no more partitions
        if (k < 0)  return;
  
        // Decrease the p[k] found above and adjust the rem_val
        p[k]--;
        rem_val++;
  
  
        // If rem_val is more, then the sorted order is violated.  Divide
        // rem_val in different values of size p[k] and copy these values at
        // different positions after p[k]
        while (rem_val > p[k])
        {
            p[k+1] = p[k];
            rem_val = rem_val - p[k];
            k++;
        }
  
        // Copy rem_val to next position and increment position
        p[k+1] = rem_val;
        k++;
    }
}
  
// Driver program to test above functions
int main()
{
    cout << "All Unique Partitions of 2 \n";
    printAllUniqueParts(2);
  
    cout << "\nAll Unique Partitions of 3 \n";
    printAllUniqueParts(3);
  
    cout << "\nAll Unique Partitions of 4 \n";
    printAllUniqueParts(4);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to generate all unique
// partitions of an integer
import java.io.*;
  
class GFG 
{
    // Function to print an array p[] of size n
    static void printArray(int p[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(p[i]+" ");
        System.out.println();
    }
      
    // Function to generate all unique partitions of an integer
    static void printAllUniqueParts(int n)
    {
        int[] p = new int[n]; // An array to store a partition
        int k = 0// Index of last element in a partition
        p[k] = n;  // Initialize first partition as number itself
   
        // This loop first prints current partition, then generates next
        // partition. The loop stops when the current partition has all 1s
        while (true)
        {
            // print current partition
            printArray(p, k+1);
   
            // Generate next partition
   
            // Find the rightmost non-one value in p[]. Also, update the
            // rem_val so that we know how much value can be accommodated
            int rem_val = 0;
            while (k >= 0 && p[k] == 1)
            {
                rem_val += p[k];
                k--;
            }
   
            // if k < 0, all the values are 1 so there are no more partitions
            if (k < 0return;
   
            // Decrease the p[k] found above and adjust the rem_val
            p[k]--;
            rem_val++;
   
   
            // If rem_val is more, then the sorted order is violeted.  Divide
            // rem_val in differnt values of size p[k] and copy these values at
            // different positions after p[k]
            while (rem_val > p[k])
            {
                p[k+1] = p[k];
                rem_val = rem_val - p[k];
                k++;
            }
   
            // Copy rem_val to next position and increment position
            p[k+1] = rem_val;
            k++;
        }
    }
      
    // Driver program
    public static void main (String[] args) 
    {
        System.out.println("All Unique Partitions of 2");
        printAllUniqueParts(2);
          
        System.out.println("All Unique Partitions of 3");
        printAllUniqueParts(3);
          
        System.out.println("All Unique Partitions of 4");
        printAllUniqueParts(4);
    }
}
  
// Contributed by Pramod Kumar

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A utility function to print an
# array p[] of size 'n'
def printArray(p, n):
    for i in range(0, n):
        print(p[i], end = " ")
    print()
  
def printAllUniqueParts(n):
    p = [0] * # An array to store a partition
    k = 0        # Index of last element in a partition
    p[k] = n     # Initialize first partition
                 # as number itself
  
    # This loop first prints current partition, 
    # then generates next partition.The loop 
    # stops when the current partition has all 1s
    while True:
          
            # print current partition
            printArray(p, k + 1)
  
            # Generate next partition
  
            # Find the rightmost non-one value in p[]. 
            # Also, update the rem_val so that we know
            # how much value can be accommodated
            rem_val = 0
            while k >= 0 and p[k] == 1:
                rem_val += p[k]
                k -= 1
  
            # if k < 0, all the values are 1 so 
            # there are no more partitions
            if k < 0:
                print()
                return
  
            # Decrease the p[k] found above 
            # and adjust the rem_val
            p[k] -= 1
            rem_val += 1
  
            # If rem_val is more, then the sorted 
            # order is violated. Divide rem_val in 
            # different values of size p[k] and copy 
            # these values at different positions after p[k]
            while rem_val > p[k]:
                p[k + 1] = p[k]
                rem_val = rem_val - p[k]
                k += 1
  
            # Copy rem_val to next position 
            # and increment position
            p[k + 1] = rem_val
            k += 1
  
# Driver Code
print('All Unique Partitions of 2')
printAllUniqueParts(2)
  
print('All Unique Partitions of 3')
printAllUniqueParts(3)
  
print('All Unique Partitions of 4')
printAllUniqueParts(4)
  
# This code is contributed 
# by JoshuaWorthington

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to generate all unique
// partitions of an integer
using System;
  
class GFG {
      
    // Function to print an array p[] 
    // of size n
    static void printArray(int []p, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(p[i]+" ");
              
        Console.WriteLine();
    }
      
    // Function to generate all unique 
    // partitions of an integer
    static void printAllUniqueParts(int n)
    {
          
        // An array to store a partition
        int[] p = new int[n]; 
          
        // Index of last element in a 
        // partition
        int k = 0; 
          
        // Initialize first partition as 
        // number itself
        p[k] = n; 
  
        // This loop first prints current 
        // partition, then generates next
        // partition. The loop stops when 
        // the current partition has all 1s
        while (true)
        {
              
            // print current partition
            printArray(p, k+1);
  
            // Generate next partition
  
            // Find the rightmost non-one 
            // value in p[]. Also, update 
            // the rem_val so that we know
            // how much value can be 
            // accommodated
            int rem_val = 0;
              
            while (k >= 0 && p[k] == 1)
            {
                rem_val += p[k];
                k--;
            }
  
            // if k < 0, all the values are 1 so
            // there are no more partitions
            if (k < 0) 
                return;
  
            // Decrease the p[k] found above 
            // and adjust the rem_val
            p[k]--;
            rem_val++;
  
  
            // If rem_val is more, then the sorted
            // order is violeted. Divide rem_val in
            // differnt values of size p[k] and copy
            // these values at different positions
            // after p[k]
            while (rem_val > p[k])
            {
                p[k+1] = p[k];
                rem_val = rem_val - p[k];
                k++;
            }
  
            // Copy rem_val to next position and 
            // increment position
            p[k+1] = rem_val;
            k++;
        }
    }
      
    // Driver program
    public static void Main () 
    {
        Console.WriteLine("All Unique Partitions of 2");
        printAllUniqueParts(2);
          
        Console.WriteLine("All Unique Partitions of 3");
        printAllUniqueParts(3);
          
        Console.WriteLine("All Unique Partitions of 4");
        printAllUniqueParts(4);
    }
}
  
// This code is contributed by Sam007.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to generate 
// all unique partitions 
// of an integer
  
// A utility function to 
// print an array p[] of 
// size 'n'
function printArray( $p, $n)
{
    for ($i = 0; $i < $n; $i++)
    echo $p[$i] , " ";
    echo "\n";
}
  
function printAllUniqueParts($n)
{
    // An array to store
    // a partition
    $p[$n] = array(0); 
      
    // Index of last element
    // in a partition
    $k = 0; 
      
    // Initialize first 
    // partition as number 
    // itself
    $p[$k] = $n
  
    // This loop first prints 
    // current partition, then 
    // generates next partition. 
    // The loop stops when the 
    // current partition has all 1s
    while (true)
    {
        // print current partition
        printArray($p, $k + 1);
  
        // Generate next partition
  
        // Find the rightmost non-one
        // value in p[]. Also, update 
        // the rem_val so that we know 
        // how much value can be accommodated
        $rem_val = 0;
        while ($k >= 0 && $p[$k] == 1)
        {
            $rem_val += $p[$k];
            $k--;
        }
  
        // if k < 0, all the values
        // are 1 so there are no 
        // more partitions
        if ($k < 0) return;
  
        // Decrease the p[k] found 
        // above and adjust the
        // rem_val
        $p[$k]--;
        $rem_val++;
  
  
        // If rem_val is more, then 
        // the sorted order is violated. 
        // Divide rem_val in different
        // values of size p[k] and copy 
        // these values at different
        // positions after p[k]
        while ($rem_val > $p[$k])
        {
            $p[$k + 1] = $p[$k];
            $rem_val = $rem_val - $p[$k];
            $k++;
        }
  
        // Copy rem_val to next
        // position and increment
        // position
        $p[$k + 1] = $rem_val;
        $k++;
    }
}
  
// Driver Code
echo "All Unique Partitions of 2 \n";
printAllUniqueParts(2);
  
echo "\nAll Unique Partitions of 3 \n";
printAllUniqueParts(3);
  
echo "\nAll Unique Partitions of 4 \n";
printAllUniqueParts(4);
  
// This code is contributed 
// by akt_mit
?>

chevron_right



Output:

All Unique Partitions of 2
2
1 1

All Unique Partitions of 3
3
2 1
1 1 1

All Unique Partitions of 4
4
3 1
2 2
2 1 1
1 1 1 1

This article is contributed by Hariprasad NG. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : jit_t, JoshuaWorthington