Number of subsets with zero sum - GeeksforGeeks

13 May, 2021
Given an array ‘arr’ consisting of integers, the task is to find the number of subsets such that their sum is equal to zero. Empty subset should also be considered.
Examples: 
Input : arr[] = {2, 2, -4} Output : 2 All possible subsets: {} = 0 {2} = 2 {2} = 2 {-4} = -4 {2, 2} = 4 {2, -4} = -2 {2, -4} = -4 {2, 2, -4} = 0 Since, {} and {2, 2, -4} are only possible subsets with sum 0, ans will be 2.Input : arr[] = {1, 1, 1, 1} Output : 1 {} is the only possible subset with sum 0, thus ans equals 1.  
One simple approach is to generate all possible subsets recursively and count the number of subsets with a sum equals to 0. The time complexity of this approach will be O(2^n).
A better approach will be using Dynamic programming. Let’s suppose the sum of all the elements we have selected up to index ‘i-1’ is ‘S’. So, starting from index ‘i’, we have to find the number of subsets of the sub-array{i, N-1} with sum equals -S. Let’s define dp[i][S]. It means the number of the subset of the subarray{i, N-1} of ‘arr’ with sum equals ‘-S’. If we are at ith index, we have two choices, i.e. to include it in the sum or leave it. Thus, the required recurrence relation becomes 
dp[i][s] = dp[i+1][s+arr[i]] + dp[i+1][s] 
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>#define maxSum 100#define arrSize 51using namespace std; // variable to store// states of dpint dp[arrSize][maxSum];bool visit[arrSize][maxSum]; // To find the number of subsets with sum equal to 0// Since S can be negative, we will maxSum// to it to make it positiveint SubsetCnt(int i, int s, int arr[], int n){    // Base cases    if (i == n) {        if (s == 0)            return 1;        else            return 0;    }     // Returns the value if a state is already solved    if (visit[i][s + maxSum])        return dp[i][s + maxSum];     // If the state is not visited, then continue    visit[i][s + maxSum] = 1;     // Recurrence relation    dp[i][s + maxSum] = SubsetCnt(i + 1, s + arr[i], arr, n)                        + SubsetCnt(i + 1, s, arr, n);     // Returning the value    return dp[i][s + maxSum];} // Driver functionint main(){    int arr[] = { 2, 2, 2, -4, -4 };    int n = sizeof(arr) / sizeof(int);     cout << SubsetCnt(0, 0, arr, n);}
// Java implementation of above approachclass GFG{     static int maxSum = 100;    static int arrSize = 51;     // variable to store    // states of dp    static int[][] dp = new int[arrSize][maxSum];    static boolean[][] visit = new boolean[arrSize][maxSum];     // To find the number of subsets with sum equal to 0    // Since S can be negative, we will maxSum    // to it to make it positive    static int SubsetCnt(int i, int s, int arr[], int n)    {        // Base cases        if (i == n)        {            if (s == 0)            {                return 1;            }            else            {                return 0;            }        }         // Returns the value if a state is already solved        if (visit[i][s + arrSize])        {            return dp[i][s + arrSize];        }         // If the state is not visited, then continue        visit[i][s + arrSize] = true;         // Recurrence relation        dp[i][s + arrSize] = SubsetCnt(i + 1, s + arr[i], arr, n)                + SubsetCnt(i + 1, s, arr, n);         // Returning the value        return dp[i][s + arrSize];    }     // Driver function    public static void main(String[] args)    {        int arr[] = {2, 2, 2, -4, -4};        int n = arr.length;         System.out.println(SubsetCnt(0, 0, arr, n));    }} /* This code contributed by PrinciRaj1992 */
# Python3 implementation of above approachimport numpy as np maxSum = 100arrSize = 51 # variable to store# states of dpdp = np.zeros((arrSize, maxSum));visit = np.zeros((arrSize, maxSum)); # To find the number of subsets# with sum equal to 0.# Since S can be negative,# we will maxSum to it# to make it positivedef SubsetCnt(i, s, arr, n) :         # Base cases    if (i == n) :        if (s == 0) :            return 1;        else :            return 0;         # Returns the value    # if a state is already solved    if (visit[i][s + arrSize]) :        return dp[i][s + arrSize];     # If the state is not visited,    # then continue    visit[i][s + arrSize] = 1;     # Recurrence relation    dp[i][s + arrSize ] = (SubsetCnt(i + 1, s + arr[i], arr, n) +                           SubsetCnt(i + 1, s, arr, n));     # Returning the value    return dp[i][s + arrSize]; # Driver Codeif __name__ == "__main__" :     arr = [ 2, 2, 2, -4, -4 ];    n = len(arr);     print(SubsetCnt(0, 0, arr, n)); # This code is contributed by AnkitRai01
// C# implementation of above approachusing System; class GFG{     static int maxSum = 100;    static int arrSize = 51;     // variable to store    // states of dp    static int [,]dp = new int[arrSize, maxSum];    static bool [,]visit = new bool[arrSize, maxSum];     // To find the number of subsets with sum equal to 0    // Since S can be negative, we will maxSum    // to it to make it positive    static int SubsetCnt(int i, int s, int []arr, int n)    {        // Base cases        if (i == n)        {            if (s == 0)            {                return 1;            }            else            {                return 0;            }        }         // Returns the value if a state is already solved        if (visit[i, s + arrSize])        {            return dp[i, s + arrSize];        }         // If the state is not visited, then continue        visit[i, s + arrSize] = true;         // Recurrence relation        dp[i, s + arrSize] = SubsetCnt(i + 1, s + arr[i], arr, n)                + SubsetCnt(i + 1, s, arr, n);         // Returning the value        return dp[i,s + arrSize];    }     // Driver code    public static void Main()    {        int []arr = {2, 2, 2, -4, -4};        int n = arr.Length;         Console.WriteLine(SubsetCnt(0, 0, arr, n));    }} // This code contributed by anuj_67..
<script> var maxSum = 100var arrSize = 51 // variable to store// states of dpvar dp = Array.from(Array(arrSize), ()=> Array(maxSum));var visit = Array.from(Array(arrSize), ()=> Array(maxSum)); // To find the number of subsets with sum equal to 0// Since S can be negative, we will maxSum// to it to make it positivefunction SubsetCnt(i, s, arr, n){    // Base cases    if (i == n) {        if (s == 0)            return 1;        else            return 0;    }     // Returns the value if a state is already solved    if (visit[i][s + maxSum])        return dp[i][s + maxSum];     // If the state is not visited, then continue    visit[i][s + maxSum] = 1;     // Recurrence relation    dp[i][s + maxSum] = SubsetCnt(i + 1, s + arr[i], arr, n)                        + SubsetCnt(i + 1, s, arr, n);     // Returning the value    return dp[i][s + maxSum];} // Driver functionvar arr = [2, 2, 2, -4, -4];var n = arr.length;document.write( SubsetCnt(0, 0, arr, n)); </script>
7
 
Time Complexity: O(n*S), where n is the number of elements in the array and S is the sum of all the elements. 
princiraj1992
vt_m
ankthon
itsok
subset
Arrays
Dynamic Programming
Recursion
Arrays
Dynamic Programming
Recursion
subset
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
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16