Find all distinct subset (or subsequence) sums of an array | Set-2
Last Updated :
27 Jan, 2023
Given an array of N positive integers write an efficient function to find the sum of all those integers which can be expressed as the sum of at least one subset of the given array i.e. calculate total sum of each subset whose sum is distinct using only O(sum) extra space.
Examples:
Input: arr[] = {1, 2, 3}
Output: 0 1 2 3 4 5 6
Distinct subsets of given set are {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3} and {1, 2, 3}. Sums of these subsets are 0, 1, 2, 3, 3, 5, 4, 6. After removing duplicates, we get 0, 1, 2, 3, 4, 5, 6
Input: arr[] = {2, 3, 4, 5, 6}
Output: 0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
Input: arr[] = {20, 30, 50}
Output: 0 20 30 50 70 80 100
A post using O(N*sum) and O(N*sum) space has been discussed in this post.
In this post, an approach using O(sum) space has been discussed. Create a single dp array of O(sum) space and mark the dp[a[0]] as true and the rest as false. Iterate for all the array elements in the array and then iterate from 1 to sum for each element in the array and mark all the dp[j] with true that satisfies the condition (arr[i] == j || dp[j] || dp[(j - arr[i])]). At the end print all the index that are marked true. Since arr[i]==j denotes the subset with single element and dp[(j - arr[i])] denotes the subset with element j-arr[i].
Below is the implementation of the above approach.
C++
// C++ program to find total sum of
// all distinct subset sums in O(sum) space.
#include <bits/stdc++.h>
using namespace std;
// Function to print all the distinct sum
void subsetSum(int arr[], int n, int maxSum)
{
// Declare a boolean array of size
// equal to total sum of the array
bool dp[maxSum + 1];
memset(dp, false, sizeof dp);
// Fill the first row beforehand
dp[arr[0]] = true;
// dp[j] will be true only if sum j
// can be formed by any possible
// addition of numbers in given array
// upto index i, otherwise false
for (int i = 1; i < n; i++) {
// Iterate from maxSum to 1
// and avoid lookup on any other row
for (int j = maxSum + 1; j >= 1; j--) {
// Do not change the dp array
// for j less than arr[i]
if (arr[i] <= j) {
if (arr[i] == j || dp[j] || dp[(j - arr[i])])
dp[j] = true;
else
dp[j] = false;
}
}
}
// If dp [j] is true then print
cout << 0 << " ";
for (int j = 0; j <= maxSum + 1; j++) {
if (dp[j] == true)
cout << j << " ";
}
}
// Function to find the total sum
// and print the distinct sum
void printDistinct(int a[], int n)
{
int maxSum = 0;
// find the sum of array elements
for (int i = 0; i < n; i++) {
maxSum += a[i];
}
// Function to print all the distinct sum
subsetSum(a, n, maxSum);
}
// Driver Code
int main()
{
int arr[] = { 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
printDistinct(arr, n);
return 0;
}
Java
// Java program to find total sum of
// all distinct subset sums in O(sum) space.
import java.util.*;
class Main
{
// Function to print all the distinct sum
public static void subsetSum(int arr[], int n, int maxSum)
{
// Declare a boolean array of size
// equal to total sum of the array
boolean dp[] = new boolean[maxSum + 1];
Arrays.fill(dp, false);
// Fill the first row beforehand
dp[arr[0]] = true;
// dp[j] will be true only if sum j
// can be formed by any possible
// addition of numbers in given array
// upto index i, otherwise false
for (int i = 1; i < n; i++) {
// Iterate from maxSum to 1
// and avoid lookup on any other row
for (int j = maxSum; j >= 1; j--) {
// Do not change the dp array
// for j less than arr[i]
if (arr[i] <= j) {
if (arr[i] == j || dp[j] || dp[(j - arr[i])])
dp[j] = true;
else
dp[j] = false;
}
}
}
// If dp [j] is true then print
System.out.print(0 + " ");
for (int j = 0; j <= maxSum; j++) {
if (dp[j] == true)
System.out.print(j + " ");
}
System.out.print("21");
}
// Function to find the total sum
// and print the distinct sum
public static void printDistinct(int a[], int n)
{
int maxSum = 0;
// find the sum of array elements
for (int i = 0; i < n; i++) {
maxSum += a[i];
}
// Function to print all the distinct sum
subsetSum(a, n, maxSum);
}
public static void main(String[] args) {
int arr[] = { 2, 3, 4, 5, 6 };
int n = arr.length;
printDistinct(arr, n);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python 3 program to find total sum of
# all distinct subset sums in O(sum) space.
# Function to print all the distinct sum
def subsetSum(arr, n, maxSum):
# Declare a boolean array of size
# equal to total sum of the array
dp = [False for i in range(maxSum + 1)]
# Fill the first row beforehand
dp[arr[0]] = True
# dp[j] will be true only if sum j
# can be formed by any possible
# addition of numbers in given array
# upto index i, otherwise false
for i in range(1, n, 1):
# Iterate from maxSum to 1
# and avoid lookup on any other row
j = maxSum
while(j >= 1):
# Do not change the dp array
# for j less than arr[i]
if (arr[i] <= j):
if (arr[i] == j or dp[j] or
dp[(j - arr[i])]):
dp[j] = True
else:
dp[j] = False
j -= 1
# If dp [j] is true then print
print(0, end = " ")
for j in range(maxSum + 1):
if (dp[j] == True):
print(j, end = " ")
print("21")
# Function to find the total sum
# and print the distinct sum
def printDistinct(a, n):
maxSum = 0
# find the sum of array elements
for i in range(n):
maxSum += a[i]
# Function to print all the distinct sum
subsetSum(a, n, maxSum)
# Driver Code
if __name__ == '__main__':
arr = [2, 3, 4, 5, 6]
n = len(arr)
printDistinct(arr, n)
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find total sum of
// all distinct subset sums in O(sum) space.
using System;
class GFG {
// Function to print all the distinct sum
static void subsetSum(int[] arr, int n, int maxSum)
{
// Declare a boolean array of size
// equal to total sum of the array
bool[] dp = new bool[maxSum + 1];
Array.Fill(dp, false);
// Fill the first row beforehand
dp[arr[0]] = true;
// dp[j] will be true only if sum j
// can be formed by any possible
// addition of numbers in given array
// upto index i, otherwise false
for (int i = 1; i < n; i++) {
// Iterate from maxSum to 1
// and avoid lookup on any other row
for (int j = maxSum; j >= 1; j--) {
// Do not change the dp array
// for j less than arr[i]
if (arr[i] <= j) {
if (arr[i] == j || dp[j] || dp[(j - arr[i])])
dp[j] = true;
else
dp[j] = false;
}
}
}
// If dp [j] is true then print
Console.Write(0 + " ");
for (int j = 0; j < maxSum + 1; j++) {
if (dp[j] == true)
Console.Write(j + " ");
}
Console.Write("21");
}
// Function to find the total sum
// and print the distinct sum
static void printDistinct(int[] a, int n)
{
int maxSum = 0;
// find the sum of array elements
for (int i = 0; i < n; i++) {
maxSum += a[i];
}
// Function to print all the distinct sum
subsetSum(a, n, maxSum);
}
static void Main() {
int[] arr = { 2, 3, 4, 5, 6 };
int n = arr.Length;
printDistinct(arr, n);
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// Javascript program to find total sum of
// all distinct subset sums in O(sum) space.
// Function to print all the distinct sum
function subsetSum(arr, n, maxSum)
{
// Declare a boolean array of size
// equal to total sum of the array
var dp = Array(maxSum + 1).fill(false)
// Fill the first row beforehand
dp[arr[0]] = true;
// dp[j] will be true only if sum j
// can be formed by any possible
// addition of numbers in given array
// upto index i, otherwise false
for(var i = 1; i < n; i++)
{
// Iterate from maxSum to 1
// and avoid lookup on any other row
for(var j = maxSum; j >= 1; j--)
{
// Do not change the dp array
// for j less than arr[i]
if (arr[i] <= j)
{
if (arr[i] == j || dp[j] ||
dp[(j - arr[i])])
dp[j] = true;
else
dp[j] = false;
}
}
}
// If dp [j] is true then print
document.write( 0 + " ");
for(var j = 0; j < maxSum + 1; j++)
{
if (dp[j] == true)
document.write(j + " ");
}
document.write("21");
}
// Function to find the total sum
// and print the distinct sum
function printDistinct(a, n)
{
var maxSum = 0;
// Find the sum of array elements
for(var i = 0; i < n; i++)
{
maxSum += a[i];
}
// Function to print all the distinct sum
subsetSum(a, n, maxSum);
}
// Driver Code
var arr = [ 2, 3, 4, 5, 6 ];
var n = arr.length;
printDistinct(arr, n);
// This code is contributed by importantly
</script>
Output: 0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21
Time complexity O(sum*n)
Auxiliary Space: O(sum)
Similar Reads
Find all distinct subset (or subsequence) sums of an array Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small.Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
15+ min read
Bitwise OR of sum of all subsequences of an array Given an array arr[] of length N, the task is to find the Bitwise OR of the sum of all possible subsequences from the given array. Examples: Input: arr[] = {4, 2, 5}Output: 15Explanation: All subsequences from the given array and their corresponding sums:{4} - 4{2} - 2{5} - 5{4, 2} - 6{4, 5} - 9{2,
6 min read
Sum of subsets of all the subsets of an array | O(N) Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset wi
7 min read
Number of Subsequences with Even and Odd Sum | Set 2 Given an array arr[] of size N. The task is to find the number of subsequences whose sum is even and the number of subsequences whose sum is odd.Examples: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are 2N-1 possible subsequences. The subsequences with even sum are 1) {1, 3} Su
7 min read
Find all distinct subsets of a given set using BitMasking Approach Given an array arr[] that may contain duplicates. The task is to return all possible subsets. Return only unique subsets and they can be in any order.Note: The individual subsets should be sorted.Examples: Input: arr[] = [1, 2, 2]Output: [], [1], [2], [1, 2], [2, 2], [1, 2, 2]Explanation: The total
7 min read