Sum of subsets of all the subsets of an array | O(2^N)

21 Apr, 2021
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples:  
Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 d) {1, 1} : 4 All the possible subsets of this subset will be {}, {1}, {1} and {1, 1}, Sum = 0 + 1 + 1 + 2 = 4 Thus, ans = 0 + 1 + 1 + 4 = 6Input: arr[] = {1, 4, 2, 12} Output: 513  
 
Approach: In this article, an approach with O(N * 2N) time complexity to solve the given problem will be discussed. First, generate all the possible subsets of the array. There will be 2N subsets in total. Then for each subset, find the sum of all of its subsets.For, that it can be observed that in an array of length L, every element will come exactly 2(L – 1) times in the sum of subsets. So, the contribution of each element will be 2(L – 1) times its values.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to sum of all subsets of a// given arrayvoid subsetSum(vector<int>& c, int& ans){    int L = c.size();    int mul = (int)pow(2, L - 1);    for (int i = 0; i < c.size(); i++)        ans += c[i] * mul;} // Function to generate the subsetsvoid subsetGen(int* arr, int i, int n,               int& ans, vector<int>& c){    // Base-case    if (i == n) {         // Finding the sum of all the subsets        // of the generated subset        subsetSum(c, ans);        return;    }     // Recursively accepting and rejecting    // the current number    subsetGen(arr, i + 1, n, ans, c);    c.push_back(arr[i]);    subsetGen(arr, i + 1, n, ans, c);    c.pop_back();} // Driver codeint main(){    int arr[] = { 1, 1 };    int n = sizeof(arr) / sizeof(int);     // To store the final ans    int ans = 0;    vector<int> c;     subsetGen(arr, 0, n, ans, c);    cout << ans;     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // To store the final ansstatic int ans; // Function to sum of all subsets of a// given arraystatic void subsetSum(Vector<Integer> c){    int L = c.size();    int mul = (int)Math.pow(2, L - 1);    for (int i = 0; i < c.size(); i++)        ans += c.get(i) * mul;} // Function to generate the subsetsstatic void subsetGen(int []arr, int i,                      int n, Vector<Integer> c){    // Base-case    if (i == n)    {         // Finding the sum of all the subsets        // of the generated subset        subsetSum(c);        return;    }     // Recursively accepting and rejecting    // the current number    subsetGen(arr, i + 1, n, c);    c.add(arr[i]);    subsetGen(arr, i + 1, n, c);    c.remove(0);} // Driver codepublic static void main(String []args){    int arr[] = { 1, 1 };    int n = arr.length;     Vector<Integer> c = new Vector<Integer>();     subsetGen(arr, 0, n, c);    System.out.println(ans);}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # store the answerc = []ans = 0 # Function to sum of all subsets of a# given arraydef subsetSum():    global ans    L = len(c)    mul = pow(2, L - 1)    i = 0    while ( i < len(c)):        ans += c[i] * mul        i += 1         # Function to generate the subsetsdef subsetGen(arr, i, n):     # Base-case    if (i == n) :         # Finding the sum of all the subsets        # of the generated subset        subsetSum()        return         # Recursively accepting and rejecting    # the current number    subsetGen(arr, i + 1, n)    c.append(arr[i])    subsetGen(arr, i + 1, n)    c.pop() # Driver codeif __name__ == "__main__" :     arr = [ 1, 1 ]    n = len(arr)     subsetGen(arr, 0, n)    print (ans)     # This code is contributed by Arnab Kundu
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // To store the final ansstatic int ans; // Function to sum of all subsets of a// given arraystatic void subsetSum(List<int> c){    int L = c.Count;    int mul = (int)Math.Pow(2, L - 1);    for (int i = 0; i < c.Count; i++)        ans += c[i] * mul;} // Function to generate the subsetsstatic void subsetGen(int []arr, int i,                      int n, List<int> c){    // Base-case    if (i == n)    {         // Finding the sum of all the subsets        // of the generated subset        subsetSum(c);        return;    }     // Recursively accepting and rejecting    // the current number    subsetGen(arr, i + 1, n, c);    c.Add(arr[i]);    subsetGen(arr, i + 1, n, c);    c.RemoveAt(0);} // Driver codepublic static void Main(String []args){    int []arr = { 1, 1 };    int n = arr.Length;     List<int> c = new List<int>();     subsetGen(arr, 0, n, c);    Console.WriteLine(ans);}} // This code is contributed by Rajput-Ji
<script>// javascript implementation of the approach     // To store the final ans    var ans = 0;     // Function to sum of all subsets of a    // given array    function subsetSum( c) {        var L = c.length;        var mul = parseInt( Math.pow(2, L - 1));        for (i = 0; i < c.length; i++)            ans += c[i] * mul;    }     // Function to generate the subsets    function subsetGen(arr , i , n, c) {        // Base-case        if (i == n) {             // Finding the sum of all the subsets            // of the generated subset            subsetSum(c);            return;        }         // Recursively accepting and rejecting        // the current number        subsetGen(arr, i + 1, n, c);        c.push(arr[i]);        subsetGen(arr, i + 1, n, c);        c.pop(0);    }     // Driver code             var arr = [ 1, 1 ];        var n = arr.length;         var c = [];         subsetGen(arr, 0, n, c);        document.write(ans); // This code is contributed by todaysgaurav</script>
6
 
29AjayKumar
Rajput-Ji
andrew1234
todaysgaurav
subset
Arrays
Backtracking
Greedy
Arrays
Greedy
subset
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
N Queen Problem | Backtracking-3
The Knight's tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Backtracking | Introduction