Sum of subsets of all the subsets of an array | O ( 2 ^ N ) | C ++ implementation of the approach ; Function to sum of all subsets of a given array ; Function to generate the subsets ; Base - case ; Finding the sum of all the subsets of the generated subset ; Recursively accepting and rejecting the current number ; Driver code ; To store the final ans
#include <bits/stdc++.h> NEW_LINE using namespace std ; void 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 ; } void subsetGen ( int * arr , int i , int n , int & ans , vector < int > & c ) { if ( i == n ) { subsetSum ( c , ans ) ; return ; } subsetGen ( arr , i + 1 , n , ans , c ) ; c . push_back ( arr [ i ] ) ; subsetGen ( arr , i + 1 , n , ans , c ) ; c . pop_back ( ) ; } int main ( ) { int arr [ ] = { 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int ans = 0 ; vector < int > c ; subsetGen ( arr , 0 , n , ans , c ) ; cout << ans ; return 0 ; }