Find all distinct subset (or subsequence) sums of an array in C++

C++Server Side ProgrammingProgramming

Suppose we have a set of integers. Find distinct sum, that can be formed from the subset of the given sets and print them in an ascending order. The sum of array elements is small. Consider the array elements are like [1, 2, 3]. Output will be 0, 1, 2, 3, 4, 5, 6. The distinct subsets are {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3}, the sum values are 0, 1, 2, 3, 3, 5, 4, 6.

To solve this, we will use the dynamic programming approach. When the sum of given element is small, we can make a DP table with rows containing the size of the array, and the size of the column will be sum of all elements in the given array.

Example

#include<iostream>
#include<cstring>
using namespace std;
void displaySubsetSum(int arr[], int n) {
   int sum = 0;
   for (int i=0; i<n; i++)
      sum += arr[i];
   bool table[n+1][sum+1];
   memset(table, 0, sizeof(table));
   for (int i=0; i<=n; i++)
      table[i][0] = true;
   for (int i=1; i<=n; i++) {
      table[i][arr[i-1]] = true;
      for (int j=1; j<=sum; j++) {
         if (table[i-1][j] == true) {
            table[i][j] = true;
            table[i][j + arr[i-1]] = true;
         }
      }
   }
   for (int j=0; j<=sum; j++)
      if (table[n][j]==true)
         cout << j << " ";
   }
int main() {
   int arr[] = {1, 2, 3};
   int n = sizeof(arr)/sizeof(arr[0]);
   displaySubsetSum(arr, n);
}

Output

0 1 2 3 4 5 6
raja
Published on 01-Nov-2019 06:14:35
Advertisements