Open In App

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

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 be calculated which are 0, 1, 2 and 3.

  • 0 if we do not choose any number.
  • 1 if we choose only 1.
  • 2 if we choose only 2.
  • 3 if we choose 1 and 2.

Input: arr[] = [1, 2, 3]
Output: [0, 1, 2, 3, 4, 5, 6]
Explanation: Seven distinct sums can be calculated which are 0, 1, 2, 3, 4, 5 and 6.

  • 0 if we do not choose any number.
  • 1 if we choose only 1.
  • 2 if we choose only 2.
  • 3 if we choose only 3.
  • 4 if we choose 1 and 3.
  • 5 if we choose 2 and 3.
  • 6 if we choose 1, 2 and 3.

Using Recursion – O(2^n) Time and O(n) Space

The naive solution for this problem is to generate all the subsets, store their sums in a hash set and finally return all keys from the hash set. recursively generates all possible subset sums by considering each element twice once including it in the sum and once excluding it. When index is reached at n store the current sum to hashSet and return.

Mathematically:

  • Include the current element (arr[i]) in the subset sum: distSumRec(arr, n, sum + arr[i], i + 1, s)
  • Exclude the current element from the subset sum: distSumRec(arr, n, sum, i + 1, s)
C++
// C++ program to print distinct subset sums of
// a given array.
#include<bits/stdc++.h>
using namespace std;

// Recursive function to calculate distinct subset sums
// sum: the current sum of the subset
void distSumRec(vector<int> &arr, int n, int sum,
                int i, set<int> &s) {
    if (i > n)
        return;
  
  
	// If we have considered all elements in the array, 
    // insert the current sum into the set
    if (i == n) {
        s.insert(sum);
        return;
    }

  	 // Include the current element (arr[i]) in the subset sum
    distSumRec(arr, n, sum + arr[i], i + 1, s);
  
  	// Exclude the current element from the subset sum
    distSumRec(arr, n, sum, i + 1, s);
}

// This function calls distSumRec() to generate
// distinct sum subsets and return it.
vector<int> DistinctSum(vector<int> &arr) {
  	
  	// Set to store distinct sums
    set<int> s; 
  	int n = arr.size();
  
  	// Start the recursive process with an 
  	// initial sum of 0 and index 0
    distSumRec(arr, n, 0, 0, s);

    vector<int> result;
  	for(int i : s) result.push_back(i);
  	return result;
}

int main() {
    vector<int> arr = {2, 3, 4, 5, 6};
  	
    vector<int> result = DistinctSum(arr);
  
  	for(int i : result) {
      	cout << i << " ";
    }
    return 0;
}
Java
// Java program to print distinct subset sums of a given
// array.
import java.util.*;

class GfG {

    // Recursive function to calculate distinct subset sums
    // sum: the current sum of the subset
    static void distSumRec(int[] arr, int n, int sum, int i,
                           Set<Integer> s) {
        if (i > n)
            return;

        // If we have considered all elements in the array,
        // insert the current sum into the set
        if (i == n) {
            s.add(sum);
            return;
        }

        // Include the current element (arr[i]) in the
        // subset sum
        distSumRec(arr, n, sum + arr[i], i + 1, s);

        // Exclude the current element from the subset sum
        distSumRec(arr, n, sum, i + 1, s);
    }

    // This function calls distSumRec() to generate
    // distinct sum subsets and return it.
    static List<Integer> DistinctSum(int[] arr) {
      
        // Set to store distinct sums
        Set<Integer> s = new HashSet<>();
        int n = arr.length;

        // Start the recursive process with an initial sum
        // of 0 and index 0
        distSumRec(arr, n, 0, 0, s);

        List<Integer> result = new ArrayList<>(s);
        return result;
    }

    public static void main(String[] args) {
        int[] arr = { 2, 3, 4, 5, 6 };

        List<Integer> result = DistinctSum(arr);

        for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print distinct subset sums of a given array.

# Recursive function to calculate distinct subset sums
# sum: the current sum of the subset
def distSumRec(arr, n, sum, i, s):
    if i > n:
        return
    
    # If we have considered all elements in the array,
    # insert the current sum into the set
    if i == n:
        s.add(sum)
        return
    
    # Include the current element (arr[i])
    # in the subset sum
    distSumRec(arr, n, sum + arr[i], i + 1, s)
    
    # Exclude the current element from the subset sum
    distSumRec(arr, n, sum, i + 1, s)

# This function calls distSumRec() to generate
# distinct sum subsets and return it.
def DistinctSum(arr):
  
    # Set to store distinct sums
    s = set()
    n = len(arr)

    # Start the recursive process with an initial
    # sum of 0 and index 0
    distSumRec(arr, n, 0, 0, s)

    return list(s)

arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
print(" ".join(map(str, result)))
C#
// C# program to print distinct subset sums of a given
// array.
using System;
using System.Collections.Generic;

class GfG {
  
    // Recursive function to calculate distinct subset sums
    // sum: the current sum of the subset
    static void distSumRec(int[] arr, int n, int sum, int i,
                           HashSet<int> s) {
        if (i > n)
            return;

        // If we have considered all elements in the array,
        // insert the current sum into the set
        if (i == n) {
            s.Add(sum);
            return;
        }

        // Include the current element (arr[i]) in the
        // subset sum
        distSumRec(arr, n, sum + arr[i], i + 1, s);

        // Exclude the current element from the subset sum
        distSumRec(arr, n, sum, i + 1, s);
    }

    // This function calls distSumRec() to generate
    // distinct sum subsets and return it.
    static List<int> DistinctSum(int[] arr) {
      
        // Set to store distinct sums
        HashSet<int> s = new HashSet<int>();
        int n = arr.Length;

        // Start the recursive process with an
        // initial sum of 0 and index 0
        distSumRec(arr, n, 0, 0, s);

        List<int> result = new List<int>(s);
        result.Sort();
        return result;
    }

    static void Main() {
      
        int[] arr = { 2, 3, 4, 5, 6 };

        List<int> result = DistinctSum(arr);
        foreach(int i in result) { Console.Write(i + " "); }
    }
}
JavaScript
// JavaScript program to print distinct subset sums of a
// given array.

// Recursive function to calculate distinct subset sums
// sum: the current sum of the subset
function distSumRec(arr, n, sum, i, s) {
    if (i > n)
        return;

    // If we have considered all elements in the array,
    // insert the current sum into the set
    if (i === n) {
        s.add(sum);
        return;
    }

    // Include the current element (arr[i]) in the subset
    // sum
    distSumRec(arr, n, sum + arr[i], i + 1, s);

    // Exclude the current element from the subset sum
    distSumRec(arr, n, sum, i + 1, s);
}

// This function calls distSumRec() to generate
// distinct sum subsets and return it.
function DistinctSum(arr) {

    // Set to store distinct sums
    let s = new Set();
    let n = arr.length;

    // Start the recursive process with an initial sum of 0
    // and index 0
    distSumRec(arr, n, 0, 0, s);

    return Array.from(s).sort((a, b) => a - b);
}

let arr = [ 2, 3, 4, 5, 6 ];
let result = DistinctSum(arr);
console.log(result.join(" "));

Output
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 

Using Top-Down DP (Memoization) – O(n * sum) Time and O(n * sum) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.

1. Optimal Substructure: The solution to the Distinct Subset Sum Problem can be derived from the optimal solutions of smaller subproblems.

  • Include the current element in the subset: If the current element (arr[i]) is included in the subset, the new required sum becomes sum + arr[i].
  • Exclude the current element from the subset: If the current element is excluded, the required sum remains the same.

2. Overlapping Subproblems: In this case, the subproblems overlap because the same subset sums are computed multiple times during recursion. For example, when considering an element in the set, the same sum can be encountered in different recursive calls.

  • We create a 2D memoization table memo[n+1][totalSum+1] where n is the number of elements in the array and totalSum is the sum of all the elements in the array. Each entry memo[i][sum] will store whether the sum sum can be formed by the first i elements of the array.
  • Initially, all entries are set to -1 to indicate that no subproblems have been computed yet.
  • Before computing memo[i][sum], we check if it is already computed by checking if memo[i][sum] != -1. If it’s already computed, we return the stored result; otherwise, we calculate it recursively using the inclusion/exclusion approach.
C++
// C++ program to print distinct subset sums of
// a given array.
#include <bits/stdc++.h>
using namespace std;

// Recursive function to calculate distinct subset sums
void distSumRec(vector<int> &arr, int n, int sum, 
                int i, vector<vector<int>> &memo) {
  
    // If we have considered all elements in 
  	// the array, mark this sum
    if (i == n) {
        memo[i][sum] = 1;
        return;
    }

    // If this state has already been computed,
  	// skip further processing
    if (memo[i][sum] != -1)
        return;

    // Mark the current state as visited
    memo[i][sum] = 1;

    // Include the current element (arr[i]) in the subset sum
    distSumRec(arr, n, sum + arr[i], i + 1, memo);

    // Exclude the current element from the subset sum
    distSumRec(arr, n, sum, i + 1, memo);
}

// This function calls distSumRec() to generate 
// distinct sum subsets and return them
vector<int> DistinctSum(vector<int> &arr) {
    int n = arr.size();
    
    // Calculate the maximum possible sum
    int totalSum = accumulate(arr.begin(), arr.end(), 0);

    // Memoization table initialized with -1
    vector<vector<int>> memo(n + 1, vector<int>(totalSum + 1, -1));

    // Start the recursive process with an 
  	// initial sum of 0 and index 0
    distSumRec(arr, n, 0, 0, memo);

    // Collect all distinct sums from the memo table
    vector<int> result;
    for (int i = 0; i <= totalSum; i++) {
        if (memo[n][i] == 1) {
            result.push_back(i);
        }
    }

    return result;
}

int main() {
    vector<int> arr = {2, 3, 4, 5, 6};

    vector<int> result = DistinctSum(arr);

    for (int i : result) {
        cout << i << " ";
    }
    return 0;
}
Java
// Java program to print distinct subset sums of
// a given array.

import java.util.*;

class GfG {
  
    // Recursive function to calculate distinct subset sums
    static void distSumRec(int[] arr, int n, int sum, 
                           int i, int[][] memo) {
      
        // If we have considered all elements in 
        // the array, mark this sum
        if (i == n) {
            memo[i][sum] = 1;
            return;
        }

        // If this state has already been computed,
        // skip further processing
        if (memo[i][sum] != -1)
            return;

        // Mark the current state as visited
        memo[i][sum] = 1;

        // Include the current element (arr[i]) in the subset sum
        distSumRec(arr, n, sum + arr[i], i + 1, memo);

        // Exclude the current element from the subset sum
        distSumRec(arr, n, sum, i + 1, memo);
    }

    // This function calls distSumRec() to generate 
    // distinct sum subsets and return them
    static List<Integer> DistinctSum(int[] arr) {
        int n = arr.length;

        // Calculate the maximum possible sum
        int totalSum = Arrays.stream(arr).sum();

        // Memoization table initialized with -1
        int[][] memo = new int[n + 1][totalSum + 1];
        for (int[] row : memo) {
            Arrays.fill(row, -1);
        }

        // Start the recursive process with an 
        // initial sum of 0 and index 0
        distSumRec(arr, n, 0, 0, memo);

        // Collect all distinct sums from the memo table
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i <= totalSum; i++) {
            if (memo[n][i] == 1) {
                result.add(i);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, 4, 5, 6};

        List<Integer> result = DistinctSum(arr);

        for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print distinct subset sums of
# a given array.

# Recursive function to calculate distinct subset sums
def distSumRec(arr, n, sum, i, memo):
  
    # If we have considered all elements in
    # the array, mark this sum
    if i == n:
        memo[i][sum] = 1
        return

    # If this state has already been computed,
    # skip further processing
    if memo[i][sum] != -1:
        return

    # Mark the current state as visited
    memo[i][sum] = 1

    # Include the current element (arr[i]) in the subset sum
    distSumRec(arr, n, sum + arr[i], i + 1, memo)

    # Exclude the current element from the subset sum
    distSumRec(arr, n, sum, i + 1, memo)

# This function calls distSumRec() to generate
# distinct sum subsets and return them

def DistinctSum(arr):
    n = len(arr)

    # Calculate the maximum possible sum
    totalSum = sum(arr)

    # Memoization table initialized with -1
    memo = [[-1 for _ in range(totalSum + 1)] for _ in range(n + 1)]

    # Start the recursive process with an
    # initial sum of 0 and index 0
    distSumRec(arr, n, 0, 0, memo)

    # Collect all distinct sums from the memo table
    result = []
    for i in range(totalSum + 1):
        if memo[n][i] == 1:
            result.append(i)

    return result

if __name__ == "__main__":
    arr = [2, 3, 4, 5, 6]

    result = DistinctSum(arr)

    for i in result:
        print(i, end=" ")
C#
// C# program to print distinct subset sums of
// a given array.

using System;
using System.Collections.Generic;

class GfG {
  
    // Recursive function to calculate distinct subset sums
    static void distSumRec(int[] arr, int n, int sum, 
                           int i, int[,] memo) {
      
        // If we have considered all elements in 
        // the array, mark this sum
        if (i == n) {
            memo[i, sum] = 1;
            return;
        }

        // If this state has already been computed,
        // skip further processing
        if (memo[i, sum] != -1)
            return;

        // Mark the current state as visited
        memo[i, sum] = 1;

        // Include the current element (arr[i])
      	// in the subset sum
        distSumRec(arr, n, sum + arr[i], i + 1, memo);

        // Exclude the current element from the subset sum
        distSumRec(arr, n, sum, i + 1, memo);
    }

    // This function calls distSumRec() to generate 
    // distinct sum subsets and return them
    static List<int> DistinctSum(int[] arr) {
        int n = arr.Length;

        // Calculate the maximum possible sum
        int totalSum = 0;
        foreach (var num in arr) {
            totalSum += num;
        }

        // Memoization table initialized with -1
        int[,] memo = new int[n + 1, totalSum + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= totalSum; j++) {
                memo[i, j] = -1;
            }
        }

        // Start the recursive process with an 
        // initial sum of 0 and index 0
        distSumRec(arr, n, 0, 0, memo);

        // Collect all distinct sums from 
      	// the memo table
        List<int> result = new List<int>();
        for (int i = 0; i <= totalSum; i++) {
            if (memo[n, i] == 1) {
                result.Add(i);
            }
        }

        return result;
    }

    static void Main() {
        int[] arr = {2, 3, 4, 5, 6};

        List<int> result = DistinctSum(arr);
        foreach (int sum in result) {
            Console.Write(sum + " ");
        }
    }
}
JavaScript
// JavaScript program to print distinct subset sums of
// a given array.

// Recursive function to calculate distinct subset sums
function distSumRec(arr, n, sum, i, memo) {

    // If we have considered all elements in
    // the array, mark this sum
    if (i === n) {
        memo[i][sum] = 1;
        return;
    }

    // If this state has already been computed,
    // skip further processing
    if (memo[i][sum] !== -1) {
        return;
    }

    // Mark the current state as visited
    memo[i][sum] = 1;

    // Include the current element (arr[i]) in the subset
    // sum
    distSumRec(arr, n, sum + arr[i], i + 1, memo);

    // Exclude the current element from the subset sum
    distSumRec(arr, n, sum, i + 1, memo);
}

// This function calls distSumRec() to generate
// distinct sum subsets and return them
function DistinctSum(arr) {

    const n = arr.length;

    // Calculate the maximum possible sum
    const totalSum = arr.reduce((acc, num) => acc + num, 0);

    // Memoization table initialized with -1
    const memo
        = Array.from({length : n + 1},
                     () => Array(totalSum + 1).fill(-1));

    // Start the recursive process with an
    // initial sum of 0 and index 0
    distSumRec(arr, n, 0, 0, memo);

    // Collect all distinct sums from the memo table
    const result = [];
    for (let i = 0; i <= totalSum; i++) {
        if (memo[n][i] === 1) {
            result.push(i);
        }
    }

    return result;
}

const arr = [ 2, 3, 4, 5, 6 ];

const result = DistinctSum(arr);
console.log(result.join(" "));

Output
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 

Using Bottom-Up DP (Tabulation) – O(n * sum) Time and O(n * sum) Space

The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.

We will create a 2D array dp[][] of size (n + 1) x (sum + 1) where sum is the sum of all elements in the array. Each dp[i][j] represents whether a subset of the first i elements of the array can sum to j. dp[i][j] = true means that there is a subset of elements from arr[0..i-1] that sums to j.

Base case:

  • We always have a subset with sum 0, which is the empty subset. Therefore, we initialize the first column dp[i][0] = true for all i, as the sum of 0 is always achievable with the empty subset.

For every element arr[i-1], we will either include or exclude it in the subset sum, and update the table accordingly.

  • Including the Element: If we include arr[i-1], then the new sum becomes j + arr[i-1]. So, we will check the previous state dp[i-1][j-arr[i-1]] to see if that sum was possible.
  • Excluding the Element: If we exclude arr[i-1], then the sum remains j, and we will check the previous state dp[i-1][j] to see if that sum was possible without including the element.
C++
// C++ program to print distinct subset sums of
// a given array.
#include <bits/stdc++.h>
using namespace std;

// Uses Dynamic Programming to find distinct
// subset sums
vector<int> DistinctSum(vector<int> &arr) {

    int n = arr.size();
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];

    // dp[i][j] would be true if arr[0..i-1] has
    // a subset with sum equal to j.
    vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1));

    // There is always a subset with 0 sum
    for (int i = 0; i <= n; i++)
        dp[i][0] = true;

    // Fill dp[][] in bottom up manner
    for (int i = 1; i <= n; i++) {
        dp[i][arr[i - 1]] = true;
        for (int j = 1; j <= sum; j++) {

            // Sums that were achievable
            // without current array element
            if (dp[i - 1][j] == true) {
                dp[i][j] = true;
                dp[i][j + arr[i - 1]] = true;
            }
        }
    }

    vector<int> result;
    for (int j = 0; j <= sum; j++)
        if (dp[n][j] == true)
            result.push_back(j);

    return result;
}

int main() {

    vector<int> arr = {2, 3, 4, 5, 6};
    vector<int> res = DistinctSum(arr);
    for (int i : res)
        cout << i << " ";
    return 0;
}
Java
// Java program to print distinct subset sums of
// a given array using dynamic programming.

import java.util.*;

class GfG {

    // Uses Dynamic Programming to find 
  	// distinct subset sums
    static List<Integer> DistinctSum(int[] arr) {
        int n = arr.length;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += arr[i];
        }

        // dp[i][j] would be true if arr[0..i-1] has a
        // subset with sum equal to j.
        boolean[][] dp = new boolean[n + 1][sum + 1];

        // There is always a subset with 0 sum
        for (int i = 0; i <= n; i++) {
            dp[i][0] = true;
        }

        // Fill dp[][] in bottom up manner
        for (int i = 1; i <= n; i++) {
            dp[i][arr[i - 1]] = true;
            for (int j = 1; j <= sum; j++) {
              
                // Sums that were achievable without the
                // current array element
                if (dp[i - 1][j] == true) {
                    dp[i][j] = true;
                    dp[i][j + arr[i - 1]] = true;
                }
            }
        }

        List<Integer> result = new ArrayList<>();
        for (int j = 0; j <= sum; j++) {
            if (dp[n][j]) {
                result.add(j);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] arr = { 2, 3, 4, 5, 6 };
        List<Integer> result = DistinctSum(arr);

        for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print distinct subset sums of
# a given array using dynamic programming.

# Uses Dynamic Programming to find distinct
# subset sums
def DistinctSum(arr):
    n = len(arr)
    total_sum = sum(arr)

    # dp[i][j] would be true if arr[0..i-1] has a
    # subset with sum equal to j.
    dp = [[False] * (total_sum + 1) for _ in range(n + 1)]

    # There is always a subset with 0 sum
    for i in range(n + 1):
        dp[i][0] = True

    # Fill dp[][] in bottom up manner
    for i in range(1, n + 1):
        dp[i][arr[i - 1]] = True
        for j in range(1, total_sum + 1):
          
            # Sums that were achievable without the
            # current array element
            if dp[i - 1][j]:
                dp[i][j] = True
                dp[i][j + arr[i - 1]] = True

    result = [j for j in range(total_sum + 1) if dp[n][j]]
    return result


arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
print(" ".join(map(str, result)))
C#
// C# program to print distinct subset sums of
// a given array using dynamic programming.
using System;
using System.Collections.Generic;

class GfG {
  
    // Uses Dynamic Programming to find
   // distinct subset sums
    static List<int> DistinctSum(int[] arr) {
        int n = arr.Length;
        int sum = 0;
        foreach(int num in arr) sum += num;

        // dp[i][j] would be true if arr[0..i-1]
        // has a subset with sum equal to j.
        bool[, ] dp = new bool[n + 1, sum + 1];

        // There is always a subset with 0 sum
        for (int i = 0; i <= n; i++) {
            dp[i, 0] = true;
        }

        // Fill dp[][] in bottom up manner
        for (int i = 1; i <= n; i++) {
            dp[i, arr[i - 1]] = true;
            for (int j = 1; j <= sum; j++) {
              
                // Sums that were achievable without the
                // current array element
                if (dp[i - 1, j]) {
                    dp[i, j] = true;
                    dp[i, j + arr[i - 1]] = true;
                }
            }
        }

        List<int> result = new List<int>();
        for (int j = 0; j <= sum; j++) {
            if (dp[n, j]) {
                result.Add(j);
            }
        }

        return result;
    }

    static void Main() {
      
        int[] arr = { 2, 3, 4, 5, 6 };
        List<int> result = DistinctSum(arr);

        foreach(int i in result) { Console.Write(i + " "); }
    }
}
JavaScript
// JavaScript program to print distinct subset sums
// of a given array using dynamic programming.

// Uses Dynamic Programming to find distinct subset sums
function DistinctSum(arr) {

    const n = arr.length;
    const totalSum = arr.reduce((acc, num) => acc + num, 0);

    // dp[i][j] would be true if arr[0..i-1] has a
    // subset with sum equal to j.
    let dp
        = Array.from({length : n + 1},
                     () => Array(totalSum + 1).fill(false));

    // There is always a subset with 0 sum
    for (let i = 0; i <= n; i++) {
        dp[i][0] = true;
    }

    // Fill dp[][] in bottom up manner
    for (let i = 1; i <= n; i++) {
        dp[i][arr[i - 1]] = true;
        for (let j = 1; j <= totalSum; j++) {

            // Sums that were achievable without the current
            // array element
            if (dp[i - 1][j]) {
                dp[i][j] = true;
                dp[i][j + arr[i - 1]] = true;
            }
        }
    }

    let result = [];
    for (let j = 0; j <= totalSum; j++) {
        if (dp[n][j]) {
            result.push(j);
        }
    }

    return result;
}

let arr = [ 2, 3, 4, 5, 6 ];
let result = DistinctSum(arr);
console.log(result.join(" "));

Output
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 

Optimized Bit-set Approach:

  • dp = dp | dp << a[i]

Above Code snippet does the same as naive solution, where dp is a bit mask (we’ll use bit-set). Lets see how:

  1. dp ? all the sums which were produced before element a[i]
  2. dp << a[i] ? shifting all the sums by a[i], i.e. adding a[i] to all the sums.
    1. For example, Suppose initially the bit-mask was 000010100 meaning we could generate only 2 and 4 (count from right).
    2. Now if we get a element 3, we could make 5 and 7 as well by adding to 2 and 4 respectively.
    3. This can be denoted by 010100000 which is equivalent to (000010100) << 3
  3. dp | (dp << a[i]) ? 000010100 | 010100000 = 010110100 This is union of above two sums representing which sums are possible, namely 2, 4, 5 and 7.
find-all-distinct-subset-or-subsequence-sums-of-an-array C++
// C++ program to compute all possible 
// distinct subset sums using BitSet

#include <bits/stdc++.h>
using namespace std;

// Function to compute all possible 
// distinct subset sums using bitset
vector<int> DistinctSum(vector<int> &arr) {
    int n = arr.size();  
  
  	// Calculate total sum of the array
    int sum = accumulate(arr.begin(), arr.end(), 0);  

    // Bitset of size sum+1, dp[i] is 1 
  	// if sum i is possible, 0 otherwise
    bitset<100001> dp; 
  
  	// Sum 0 is always possible (empty subset)
    dp[0] = 1; 

    for (int i = 0; i < n; ++i) {
      
      	// Shift the current possible sums by a[i]
        dp |= dp << arr[i];
    }

    // Collect all the sums that are possible
    vector<int> res;
    for (int i = 0; i <= sum; ++i) {
        if (dp[i]) {
          
          	// If dp[i] is 1, it means sum i is possible
            res.push_back(i); 
        }
    }

    return res;
}

int main() {
  
    vector<int> arr = {2, 3, 4, 5, 6};
    
    vector<int> result = DistinctSum(arr);
    for (int sum : result) {
        cout << sum << " ";
    }
    return 0;
}
Java
// Java program to compute all possible 
// distinct subset sums using BitSet
import java.util.*;

class GfG {

    // Function to compute all possible 
    // distinct subset sums using BitSet
    static List<Integer> DistinctSum(int[] arr) {
        int n = arr.length;

        // Calculate total sum of the array
        int sum = Arrays.stream(arr).sum();

        // BitSet of size sum+1, dp[i] is 1 
        // if sum i is possible, 0 otherwise
        BitSet dp = new BitSet(sum + 1);

        // Sum 0 is always possible (empty subset)
        dp.set(0);

        for (int i = 0; i < n; ++i) {
          
            // Create a copy of the current dp state
            BitSet temp = (BitSet) dp.clone();

            // Add the current element to the previously
          	// possible sums
            for (int j = 0; j <= sum; ++j) {
                if (dp.get(j)) {
                    temp.set(j + arr[i]);
                }
            }

            // Update dp with the new sums
            dp.or(temp);
        }

        // Collect all the sums that are possible
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i <= sum; ++i) {
            if (dp.get(i)) {
              
                // If dp[i] is 1, it means sum i is possible
                res.add(i);
            }
        }
      

        return res;
    }

    public static void main(String[] args) {
      
        int[] arr = {2, 3, 4, 5, 6};
        List<Integer> result = DistinctSum(arr);
        for (int sum : result) {
            System.out.print(sum + " ");
        }
    }
}
Python
# Python program to compute all possible
# distinct subset sums using bitset

# Function to compute all possible 
# distinct subset sums using bitset
def DistinctSum(arr):
    n = len(arr)
    
    # Calculate total sum of the array
    total_sum = sum(arr)
    
    # Bitset of size total_sum+1, dp[i] is 1 if
    # sum i is possible, 0 otherwise
    dp = [False] * (total_sum + 1)
    
    # Sum 0 is always possible (empty subset)
    dp[0] = True

    for num in arr:
      
        # Shift the current possible sums by num
        for j in range(total_sum, num - 1, -1):
            if dp[j - num]:
                dp[j] = True

    # Collect all the sums that are possible
    result = [i for i in range(total_sum + 1) if dp[i]]
    
    return result


arr = [2, 3, 4, 5, 6]
result = DistinctSum(arr)
print(" ".join(map(str, result)))
C#
// C# program to compute all possible
// distinct subset sums using BitArray

using System;
using System.Collections;
using System.Collections.Generic;

class GfG {
  
    // Function to compute all possible
    // distinct subset sums using BitArray
    static List<int> DistinctSum(int[] arr) {
        int n = arr.Length;

        // Calculate total sum of the array
        int sum = 0;
        foreach(var num in arr) sum += num;

        // BitArray of size sum+1, dp[i] is 1 if
        // sum i is possible, 0 otherwise
        BitArray dp = new BitArray(sum + 1);

        // Sum 0 is always possible (empty subset)
        dp[0] = true;

        for (int i = 0; i < n; ++i) {
          
            // Create a clone of the current dp state
            BitArray temp = (BitArray)dp.Clone();
            for (int j = 0; j <= sum - arr[i]; ++j) {
                if (dp[j]) {
                    temp[j + arr[i]] = true;
                }
            }
          
            // Update dp with the new sums
            dp = temp;
        }

        // Collect all the sums that are possible
        List<int> result = new List<int>();
        for (int i = 0; i <= sum; ++i) {
            if (dp[i]) {
              
                // If dp[i] is true, it means sum i is
                // possible
                result.Add(i);
            }
        }

        return result;
    }

    static void Main() {
      
        int[] arr = { 2, 3, 4, 5, 6 };

        List<int> result = DistinctSum(arr);
        foreach(int sum in result) {
            Console.Write(sum + " ");
        }
    }
}
JavaScript
// JavaScript program to compute all possible
// distinct subset sums using bitset

// Function to compute all possible
// distinct subset sums using bitset
function DistinctSum(arr) {

    const n = arr.length;

    // Calculate total sum of the array
    const totalSum = arr.reduce((acc, num) => acc + num, 0);

    // Bitset of size totalSum+1, dp[i] is 1
    // if sum i is possible, 0 otherwise
    let dp = Array(totalSum + 1).fill(false);

    // Sum 0 is always possible (empty subset)
    dp[0] = true;

    for (let i = 0; i < n; ++i) {
    
        // Shift the current possible sums by a[i]
        for (let j = totalSum; j >= arr[i]; --j) {
            if (dp[j - arr[i]]) {
                dp[j] = true;
            }
        }
    }

    // Collect all the sums that are possible
    let result = [];
    for (let i = 0; i <= totalSum; ++i) {
        if (dp[i]) {
            result.push(i);
        }
    }

    return result;
}

let arr = [ 2, 3, 4, 5, 6 ];
let result = DistinctSum(arr);
console.log(result.join(" "));

Output
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 

Time Complexity: also seems to be O(n * s). Because if we would have used a array instead of bitset the shifting would have taken linear time O(S). However the shift (and almost all) operation on bitset takes O(s / w) time. Where w is the word size of the system, Usually its 32 bit or 64 bit. Thus the final time complexity becomes O(n * s / w)

Auxiliary Space:O(m),  where m is the maximum value of the input array.

Some Important Points:

  1. The size of bitset must be a constant, this sometimes is a drawback as we might waste some space.
  2. Bitset can be thought of a array where every element takes care of W elements. For example 010110100 is equivalent to {2, 6, 4} in a hypothetical system with word size w = 3.
  3. Bitset optimized knapsack solution reduced the time complexity by a factor of w which sometimes is just enough to get AC.
     


Next Article

Similar Reads