Sum of subsets of all the subsets of an array | O ( 3 ^ N ) | C ++ implementation of the approach ; To store the final ans ; Function to sum of all subsets of a given array ; Base case ; Recursively calling subsetSum ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 ; vector < int > c ; subsetGen ( arr , 0 , n , ans , c ) ; cout << ans ; return 0 ; } void subsetSum ( vector < int > & c , int i , int & ans , int curr ) { if ( i == c . size ( ) ) { ans += curr ; return ; } subsetSum ( c , i + 1 , ans , curr + c [ i ] ) ; subsetSum ( c , i + 1 , ans , curr ) ; } void subsetGen ( int * arr , int i , int n , int & ans , vector < int > & c ) { if ( i == n ) { subsetSum ( c , 0 , ans , 0 ) ; 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 ) ;