Sum of subsets of all the subsets of an array | O ( 3 ^ N ) | Java 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
import java . util . * ; class GFG { static Vector < Integer > c = new Vector < > ( ) ; static int ans = 0 ; static void subsetSum ( int i , int curr ) { if ( i == c . size ( ) ) { ans += curr ; return ; } subsetSum ( i + 1 , curr + c . elementAt ( i ) ) ; subsetSum ( i + 1 , curr ) ; } static void subsetGen ( int [ ] arr , int i , int n ) { if ( i == n ) { subsetSum ( 0 , 0 ) ; return ; } subsetGen ( arr , i + 1 , n ) ; c . add ( arr [ i ] ) ; subsetGen ( arr , i + 1 , n ) ; c . remove ( c . size ( ) - 1 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 1 } ; int n = arr . length ; subsetGen ( arr , 0 , n ) ; System . out . println ( ans ) ; } }