Count of subsets with sum equal to X | Set-2 - GeeksforGeeks

11 Feb, 2022
Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X.
Examples: 
Input: arr[] = {1, 2, 3, 3}, X = 6 Output: 3 Explanation: All the possible subsets are {1, 2, 3}, {1, 2, 3} and {3, 3}.
Input: arr[] = {1, 1, 1, 1}, X = 1 Output: 4 
Space Efficient Approach: This problem has already been discussed in the article here. This article focuses on a similar Dynamic Programming approach which uses only O(X) space. The standard DP relation of solving this problem as discussed in the above article is:
dp[i][C] = dp[i – 1][C – arr[i]] + dp[i – 1][C] 
where dp[i][C] stores the number of subsets of the subarray arr[0... i] such that their sum is equal to C. It can be noted that the dp[i]th state only requires the array values of the dp[i – 1]th state. Hence the above relation can be simplified into the following:
dp[C] = dp[C – arr[i]] + dp[C]
Here, a good point to note is that during the calculation of dp[C], the variable C must be iterated in decreasing order in order to avoid the duplicity of arr[i] in the subset-sum count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of subsets// having the given sumint subsetSum(int arr[], int n, int sum){    // Initializing the dp-table    int dp[sum + 1] = {};     // Case for sum of elements in empty set    dp[0] = 1;     // Loop to iterate over array elements    for (int i = 0; i < n; i++) {        for (int j = sum; j >= 0; j--) {             // If j-arr[i] is a valid index            if (j - arr[i] >= 0) {                dp[j] = dp[j - arr[i]] + dp[j];            }        }    }     // Return answer    return dp[sum];} // Driven Codeint main(){    int arr[] = { 1, 1, 1, 1 };    int N = sizeof(arr) / sizeof(arr[0]);    int sum = 1;     cout << subsetSum(arr, N, sum) << endl;     return 0;}
// Java implementation of the above approachimport java.util.*;public class GFG{   // Function to find the count of subsets// having the given sumstatic int subsetSum(int arr[], int n, int sum){    // Initializing the dp-table    int dp[] = new int[sum + 1];     // Case for sum of elements in empty set    dp[0] = 1;     // Loop to iterate over array elements    for (int i = 0; i < n; i++) {        for (int j = sum; j >= 0; j--) {             // If j-arr[i] is a valid index            if (j - arr[i] >= 0) {                dp[j] = dp[j - arr[i]] + dp[j];            }        }    }     // Return answer    return dp[sum];} // Driver codepublic static void main(String args[]){    int arr[] = { 1, 1, 1, 1 };    int N = arr.length;    int sum = 1;         System.out.println(subsetSum(arr, N, sum));}} // This code is contributed by Samim Hossain Mondal.
# Python implementation of the above approach # Function to find the count of subsets# having the given sumdef subsetSum(arr, n, sum):     # Initializing the dp-table    dp = [0] * (sum + 1)     # Case for sum of elements in empty set    dp[0] = 1;     # Loop to iterate over array elements    for i in range(n):        for j in range(sum, 0, -1):             # If j-arr[i] is a valid index            if (j - arr[i] >= 0):                dp[j] = dp[j - arr[i]] + dp[j];    # Return answer    return dp[sum]; # Driven Codearr = [1, 1, 1, 1];N = len(arr)sum = 1; print(subsetSum(arr, N, sum)) # This code is contributed by gfgking.
// C# implementation of the above approachusing System; public class GFG{   // Function to find the count of subsets// having the given sumstatic int subsetSum(int []arr, int n, int sum){       // Initializing the dp-table    int []dp = new int[sum + 1];     // Case for sum of elements in empty set    dp[0] = 1;     // Loop to iterate over array elements    for (int i = 0; i < n; i++) {        for (int j = sum; j >= 0; j--) {             // If j-arr[i] is a valid index            if (j - arr[i] >= 0) {                dp[j] = dp[j - arr[i]] + dp[j];            }        }    }     // Return answer    return dp[sum];} // Driver codepublic static void Main(String []args){    int []arr = { 1, 1, 1, 1 };    int N = arr.Length;    int sum = 1;         Console.WriteLine(subsetSum(arr, N, sum));}} // This code is contributed by shikhasingrajput
<script>// Javascript implementation of the above approach // Function to find the count of subsets// having the given sumfunction subsetSum(arr, n, sum){     // Initializing the dp-table    let dp = new Array(sum + 1).fill(0)     // Case for sum of elements in empty set    dp[0] = 1;     // Loop to iterate over array elements    for (let i = 0; i < n; i++) {        for (let j = sum; j >= 0; j--) {             // If j-arr[i] is a valid index            if (j - arr[i] >= 0) {                dp[j] = dp[j - arr[i]] + dp[j];            }        }    }     // Return answer    return dp[sum];} // Driven Codelet arr = [1, 1, 1, 1];let N = arr.length;let sum = 1; document.write(subsetSum(arr, N, sum)) // This code is contributed by gfgking.</script>
4
Time Complexity: O(N * X)Auxiliary Space: O(X)
gfgking
samim2000
shikhasingrajput
sagartomar9927
prasanna1995
subset
Arrays
Dynamic Programming
Arrays
Dynamic Programming
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Bellman–Ford Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16