Print sums of all subsets of a given set

Last Updated : 25 Aug, 2026

Given an array arr[] of integers, return the sums of all subsets in the list.  Return the sums in any order.

Examples: 

Input: arr[] = [2, 3]
Output: [0, 2, 3, 5]
Explanation: When no elements are taken then Sum = 0. When only 2 is taken then Sum = 2. When only 3 is taken then Sum = 3. When elements 2 and 3 are taken then Sum = 2+3 = 5.

Input: arr[] = [1, 2, 1]
Output: [0, 1, 1, 2, 2, 3, 3, 4]
Explanation: The possible subset sums are 0 (no elements), 1 (either of the 1's), 2 (the element 2), and their combinations.

Input: arr[] = [5, 6, 7]
Output: [0, 5, 6, 7, 11, 12, 13, 18]
Explanation: The possible subset sums are 0 (no elements), 5, 6, 7, and their combinations.

Try It Yourself
redirect icon

Using Recursive Backtracking - O(2 ^ n) Time and O(n) Space

The idea is to recursively generate all possible subsets by making two choices for each element: either include the element in the subset or exclude it. Once all elements are processed, the current sum is added to the result.

Working of Approach:

  • Start from index 0 with the current sum as 0.
  • For each element, make two choices: include it or exclude it.
  • If included, add the element to the current sum and recurse.
  • If excluded, keep the current sum unchanged and recurse.
  • When all elements are processed, store the current subset sum.

Let us understand with an example:
Input: arr[] = [5, 6, 7]

  • Start with index = 0, currentSum = 0. Including 5 gives 5, while excluding it keeps the sum 0.
  • For each choice, the function similarly processes 6 and 7, generating all possible subset sums.
  • When index == arr.size(), the current sum is added to res.
  • The generated sums are [18, 11, 12, 5, 13, 6, 7, 0].
  • Finally, sort() arranges them in increasing order: [0, 5, 6, 7, 11, 12, 13, 18].
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Helper function to recursively calculate subset sums
void calculateSubsetSums(vector<int> &arr, int index, int currentSum, vector<int> &res)
{

    // If all elements are processed, store the current sum.
    if (index == arr.size())
    {
        res.push_back(currentSum);
        return;
    }

    // Include the current element in the subset.
    calculateSubsetSums(arr, index + 1, currentSum + arr[index], res);

    // Exclude the current element from the subset.
    calculateSubsetSums(arr, index + 1, currentSum, res);
}

vector<int> subsetSums(vector<int> &arr)
{
    vector<int> subsetSumsResult;

    // Generate all subset sums.
    calculateSubsetSums(arr, 0, 0, subsetSumsResult);

    // Sort the subset sums in increasing order.
    sort(subsetSumsResult.begin(), subsetSumsResult.end());

    return subsetSumsResult;
}

int main()
{
    vector<int> arr = {5, 6, 7};

    vector<int> res = subsetSums(arr);

    cout << "[";

    for (int i = 0; i < res.size(); i++)
    {
        if (i > 0)
            cout << ", ";

        cout << res[i];
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class GFG {

    static void calculateSubsetSums(int[] arr, int index,
                                    int currentSum,
                                    ArrayList<Integer> res)
    {

        // If all elements are processed, store the current
        // sum.
        if (index == arr.length) {
            res.add(currentSum);
            return;
        }

        // Include the current element in the subset.
        calculateSubsetSums(arr, index + 1,
                            currentSum + arr[index], res);

        // Exclude the current element from the subset.
        calculateSubsetSums(arr, index + 1, currentSum,
                            res);
    }

    static ArrayList<Integer> subsetSums(int[] arr)
    {
        ArrayList<Integer> subsetSumsResult
            = new ArrayList<>();

        // Generate all subset sums.
        calculateSubsetSums(arr, 0, 0, subsetSumsResult);

        // Sort the subset sums in increasing order.
        Collections.sort(subsetSumsResult);

        return subsetSumsResult;
    }

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

        ArrayList<Integer> res = subsetSums(arr);

        System.out.print("[");

        for (int i = 0; i < res.size(); i++) {
            if (i > 0)
                System.out.print(", ");

            System.out.print(res.get(i));
        }

        System.out.print("]");
    }
}
Python
def calculateSubsetSums(arr, index, currentSum, res):
    # If all elements are processed, store the current sum.
    if index == len(arr):
        res.append(currentSum)
        return

    # Include the current element in the subset.
    calculateSubsetSums(arr, index + 1, currentSum + arr[index], res)

    # Exclude the current element from the subset.
    calculateSubsetSums(arr, index + 1, currentSum, res)


def subsetSums(arr):
    subsetSumsResult = []

    # Generate all subset sums.
    calculateSubsetSums(arr, 0, 0, subsetSumsResult)

    # Sort the subset sums in increasing order.
    subsetSumsResult.sort()

    return subsetSumsResult


if __name__ == '__main__':
    arr = [5, 6, 7]
    res = subsetSums(arr)

    print('[', end='')
    for i in range(len(res)):
        if i > 0:
            print(', ', end='')
        print(res[i], end='')
    print(']')
C#
using System;
using System.Collections.Generic;

class GFG {
    static void calculateSubsetSums(int[] arr, int index,
                                    int currentSum,
                                    List<int> res)
    {
        // If all elements are processed, store the current
        // sum.
        if (index == arr.Length) {
            res.Add(currentSum);
            return;
        }

        // Include the current element in the subset.
        calculateSubsetSums(arr, index + 1,
                            currentSum + arr[index], res);

        // Exclude the current element from the subset.
        calculateSubsetSums(arr, index + 1, currentSum,
                            res);
    }

    static List<int> subsetSums(int[] arr)
    {
        List<int> subsetSumsResult = new List<int>();

        // Generate all subset sums.
        calculateSubsetSums(arr, 0, 0, subsetSumsResult);

        // Sort the subset sums in increasing order.
        subsetSumsResult.Sort();

        return subsetSumsResult;
    }

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

        List<int> res = subsetSums(arr);

        Console.Write("[");

        for (int i = 0; i < res.Count; i++) {
            if (i > 0)
                Console.Write(", ");

            Console.Write(res[i]);
        }

        Console.Write("]");
    }
}
JavaScript
function calculateSubsetSums(arr, index, currentSum, res)
{
    // If all elements are processed, store the current sum.
    if (index === arr.length) {
        res.push(currentSum);
        return;
    }

    // Include the current element in the subset.
    calculateSubsetSums(arr, index + 1,
                        currentSum + arr[index], res);

    // Exclude the current element from the subset.
    calculateSubsetSums(arr, index + 1, currentSum, res);
}

function subsetSums(arr)
{
    let subsetSumsResult = [];

    // Generate all subset sums.
    calculateSubsetSums(arr, 0, 0, subsetSumsResult);

    // Sort the subset sums in increasing order.
    subsetSumsResult.sort((a, b) => a - b);

    return subsetSumsResult;
}

// Driver Code
let arr = [ 5, 6, 7 ];
let res = subsetSums(arr);

console.log("[");

for (let i = 0; i < res.length; i++) {
    if (i > 0)
        process.stdout.write(", ");

    process.stdout.write(res[i].toString());
}

console.log("]");

Output
[0, 5, 6, 7, 11, 12, 13, 18]

Generate Subsets Using Bitmasking - O(n * 2 ^ n) Time and O(2 ^ n) Space

The idea is to use the binary representation of numbers from 0 to 2^n - 1 to represent all possible subsets. Each bit tells whether the corresponding array element is included in the subset.

Working of Approach:

  • There are 2^n possible subsets for n elements.
  • Use numbers from 0 to 2^n - 1 as subset masks.
  • For every mask, check each bit.
  • If the bit is set, add the corresponding element to the sum.
  • Store the sum of every mask in the result.
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> subsetSums(vector<int> &arr)
{
    int n = arr.size();
    vector<int> res;

    // Generate all possible subset masks.
    for (int mask = 0; mask < (1 << n); mask++)
    {
        int sum = 0;

        // Check every element for the current subset.
        for (int i = 0; i < n; i++)
        {

            // If the i-th bit is set, include arr[i].
            if (mask & (1 << i))
                sum += arr[i];
        }

        // Store the sum of the current subset.
        res.push_back(sum);
    }

    return res;
}

int main()
{

    vector<int> arr = {5, 6, 7};

    vector<int> res = subsetSums(arr);

    cout << "[";

    for (int i = 0; i < res.size(); i++)
    {
        if (i > 0)
            cout << ", ";

        cout << res[i];
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class GFG {

    static ArrayList<Integer> subsetSums(int[] arr)
    {
        int n = arr.length;
        ArrayList<Integer> res = new ArrayList<>();

        // Generate all possible subset masks.
        for (int mask = 0; mask < (1 << n); mask++) {
            int sum = 0;

            // Check every element for the current subset.
            for (int i = 0; i < n; i++) {

                // If the i-th bit is set, include arr[i].
                if ((mask & (1 << i)) != 0)
                    sum += arr[i];
            }

            // Store the sum of the current subset.
            res.add(sum);
        }

        return res;
    }

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

        ArrayList<Integer> res = subsetSums(arr);

        System.out.print("[");

        for (int i = 0; i < res.size(); i++) {
            if (i > 0)
                System.out.print(", ");

            System.out.print(res.get(i));
        }

        System.out.print("]");
    }
}
Python
def subsetSums(arr):
    n = len(arr)
    res = []

    # Generate all possible subset masks.
    for mask in range(1 << n):
        sum = 0

        # Check every element for the current subset.
        for i in range(n):

            # If the i-th bit is set, include arr[i].
            if mask & (1 << i):
                sum += arr[i]

        # Store the sum of the current subset.
        res.append(sum)

    return res


if __name__ == '__main__':
    arr = [5, 6, 7]

    res = subsetSums(arr)

    print('[', end='')

    for i in range(len(res)):
        if i > 0:
            print(', ', end='')

        print(res[i], end='')

    print(']')
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> subsetSums(int[] arr)
    {
        int n = arr.Length;
        List<int> res = new List<int>();

        // Generate all possible subset masks.
        for (int mask = 0; mask < (1 << n); mask++) {
            int sum = 0;

            // Check every element for the current subset.
            for (int i = 0; i < n; i++) {
                // If the i-th bit is set, include arr[i].
                if ((mask & (1 << i)) != 0)
                    sum += arr[i];
            }

            // Store the sum of the current subset.
            res.Add(sum);
        }

        return res;
    }

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

        List<int> res = subsetSums(arr);

        Console.Write("[");

        for (int i = 0; i < res.Count; i++) {
            if (i > 0)
                Console.Write(", ");

            Console.Write(res[i]);
        }

        Console.Write("]");
    }
}
JavaScript
function subsetSums(arr)
{
    let n = arr.length;
    let res = [];

    // Generate all possible subset masks.
    for (let mask = 0; mask < (1 << n); mask++) {
        let sum = 0;

        // Check every element for the current subset.
        for (let i = 0; i < n; i++) {

            // If the i-th bit is set, include arr[i].
            if (mask & (1 << i)) {
                sum += arr[i];
            }
        }

        // Store the sum of the current subset.
        res.push(sum);
    }

    return res;
}

// Driver Code
const arr = [ 5, 6, 7 ];
const res = subsetSums(arr);

console.log("[");

for (let i = 0; i < res.length; i++) {
    if (i > 0) {
        console.log(", ", res[i]);
    }
    else {
        console.log(res[i]);
    }
}

console.log("]");

Output
[0, 5, 6, 11, 7, 12, 13, 18]

Iteratively Build Subset Sums - O(2 ^ n) Time and O(2 ^ n) Space

The idea is to start with the sum of the empty subset, 0. For every element, add it to each sum already present and append these new sums to the result.

Working of Approach:

  • Start with result = [0].
  • Process each element one by one.
  • Store the current size of the result.
  • Add the current element to every existing sum.
  • Append these new sums to the result.
C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> subsetSums(vector<int> &arr)
{
    vector<int> res = {0};

    // Process each element of the array.
    for (int x : arr)
    {
        int size = res.size();

        // Create new subset sums by including the current element.
        for (int i = 0; i < size; i++)
        {
            res.push_back(res[i] + x);
        }
    }

    return res;
}

int main()
{

    vector<int> arr = {5, 6, 7};

    vector<int> res = subsetSums(arr);

    cout << "[";

    for (int i = 0; i < res.size(); i++)
    {
        if (i > 0)
            cout << ", ";

        cout << res[i];
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class GFG {

    static ArrayList<Integer> subsetSums(int[] arr)
    {
        ArrayList<Integer> res = new ArrayList<>();
        res.add(0);

        // Process each element of the array.
        for (int x : arr) {
            int size = res.size();

            // Create new subset sums by including the
            // current element.
            for (int i = 0; i < size; i++) {
                res.add(res.get(i) + x);
            }
        }

        return res;
    }

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

        ArrayList<Integer> res = subsetSums(arr);

        System.out.print("[");

        for (int i = 0; i < res.size(); i++) {
            if (i > 0)
                System.out.print(", ");

            System.out.print(res.get(i));
        }

        System.out.print("]");
    }
}
Python
def subsetSums(arr):
    res = [0]

    # Process each element of the array.
    for x in arr:
        size = len(res)

        # Create new subset sums by including the current element.
        for i in range(size):
            res.append(res[i] + x)

    return res


if __name__ == '__main__':
    arr = [5, 6, 7]

    res = subsetSums(arr)

    print('[', end='')

    for i in range(len(res)):
        if i > 0:
            print(', ', end='')

        print(res[i], end='')

    print(']')
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<int> subsetSums(int[] arr)
    {
        List<int> res = new List<int>{ 0 };

        // Process each element of the array.
        foreach(int x in arr)
        {
            int size = res.Count;

            // Create new subset sums by including the
            // current element.
            for (int i = 0; i < size; i++) {
                res.Add(res[i] + x);
            }
        }

        return res;
    }

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

        List<int> res = subsetSums(arr);

        Console.Write("[");

        for (int i = 0; i < res.Count; i++) {
            if (i > 0)
                Console.Write(", ");

            Console.Write(res[i]);
        }

        Console.Write("]");
    }
}
JavaScript
function subsetSums(arr)
{
    let res = [ 0 ];

    // Process each element of the array.
    for (let x of arr) {
        let size = res.length;

        // Create new subset sums by including the current
        // element.
        for (let i = 0; i < size; i++) {
            res.push(res[i] + x);
        }
    }

    return res;
}

// Driver Code
let arr = [ 5, 6, 7 ];

let res = subsetSums(arr);

console.log("[");

for (let i = 0; i < res.length; i++) {
    if (i > 0)
        console.log(", ");

    console.log(res[i]);
}

console.log("]");

Output
[0, 5, 6, 11, 7, 12, 13, 18]
Comment