Partition problem

For this problem, a given set can be partitioned in such a way, that sum of each subset is equal.

At first, we have to find the sum of the given set. If it is even, then there is a chance to divide it into two sets. Otherwise, it cannot be divided.

For even value of the sum, then we will create a table named partTable, now use the following condition to solve the problem.

partTable[i, j] is true, when subset of array[0] to array[j-1] has sum equal to i, otherwise it is false.

Input and Output

Input:
A set of integers. {3, 1, 1, 2, 2, 1}
Output:
True if the set can be partitioned into two parts with equal sum.
Here the answer is true. One pair of the partitions are: {3, 1, 1}, {2, 2, 1}

Algorithm

checkPartition(set, n)

Input − The given set, the number of elements in the set.

Output − True when partitioning is possible to make two subsets of the equal sum.

Begin
   sum := sum of all elements in the set
   if sum is odd, then
      return

   define partTable of order (sum/2 + 1 x n+1)
   set all elements in the 0th row to true
   set all elements in the 0th column to false

   for i in range 1 to sum/2, do
      for j in range 1 to n, do
         partTab[i, j] := partTab[i, j-1]
         if i >= set[j-1], then
            partTab[i, j] := partTab[i, j] or with
            partTab[i – set[j-1], j-1]
      done
   done

   return partTab[sum/2, n]
End

Example

#include 
using namespace std;

bool checkPartition (int set[], int n) {
   int sum = 0;

   for (int i = 0; i = set[j-1])
            partTab[i][j] = partTab[i][j] || partTab[i - set[j-1]][j-1];
      }      
   }  
   return partTab[sum/2][n];
}
   
int main() {
   int set[] = {3, 1, 1, 2, 2, 1};
   int n = 6;

   if (checkPartition(set, n))
      cout 

Output

Given Set can be divided into two subsets of equal sum.
Updated on: 2020-06-17T07:25:03+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements