Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Subset sum problem where Array sum is at most N
Next article icon

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

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
Subset sum problem where Array sum is at most N

K

Karan Goyal
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • subsequence
  • subset
Practice Tags :
  • Dynamic Programming
  • subset

Similar Reads

  • Subset Sum Problem
    Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: arr[] = [3, 34,
    15+ min read
  • Subset sum in Different languages

    • Python Program for Subset Sum Problem | DP-25
      Write a Python program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input:
      7 min read

    • Java Program for Subset Sum Problem | DP-25
      Write a Java program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: se
      8 min read

    • C Program for Subset Sum Problem | DP-25
      Write a C program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: set[]
      8 min read

    • PHP Program for Subset Sum Problem | DP-25
      Write a PHP program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: set
      7 min read

    • C# Program for Subset Sum Problem | DP-25
      Write a C# program for a given set of non-negative integers and a value sum, the task is to check if there is a subset of the given set whose sum is equal to the given sum. Examples: Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: set[
      8 min read

  • Subset Sum Problem using Backtracking
    Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum. Examples:  Input: set[] = {1,2,1}, sum = 3Output: [1,2],[2,1]Explanation: There are subsets [1,2],[2,1] with sum 3. Input: set[] = {3, 34, 4, 12, 5, 2}, sum =
    8 min read
  • Print all subsets with given sum
    Given an array arr[] of non-negative integers and an integer target. The task is to print all subsets of the array whose sum is equal to the given target. Note: If no subset has a sum equal to target, print -1. Examples: Input: arr[] = [5, 2, 3, 10, 6, 8], target = 10Output: [ [5, 2, 3], [2, 8], [10
    15+ min read
  • Subset Sum Problem in O(sum) space
    Given an array of non-negative integers and a value sum, determine if there is a subset of the given set with sum equal to given sum. Examples: Input: arr[] = {4, 1, 10, 12, 5, 2}, sum = 9Output: TRUEExplanation: {4, 5} is a subset with sum 9. Input: arr[] = {1, 8, 2, 5}, sum = 4Output: FALSE Explan
    13 min read
  • Subset Sum is NP Complete
    Prerequisite: NP-Completeness, Subset Sum Problem Subset Sum Problem: Given N non-negative integers a1...aN and a target sum K, the task is to decide if there is a subset having a sum equal to K. Explanation: An instance of the problem is an input specified to the problem. An instance of the subset
    5 min read
  • Minimum Subset sum difference problem with Subset partitioning
    Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If
    13 min read
  • Maximum subset sum such that no two elements in set have same digit in them
    Given an array of N elements. Find the subset of elements which has maximum sum such that no two elements in the subset has common digit present in them.Examples: Input : array[] = {22, 132, 4, 45, 12, 223} Output : 268 Maximum Sum Subset will be = {45, 223} . All possible digits are present except
    12 min read
  • 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
  • Subset sum problem where Array sum is at most N
    Given an array arr[] of size N such that the sum of all the array elements does not exceed N, and array queries[] containing Q queries. For each query, the task is to find if there is a subset of the array whose sum is the same as queries[i]. Examples: Input: arr[] = {1, 0, 0, 0, 0, 2, 3}, queries[]
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences