Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Medium
  • Last Updated : 12 Dec, 2021

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:
Explanation: All the possible subsets are {1, 2, 3}, {1, 2, 3} and {3, 3}.

Input: arr[] = {1, 1, 1, 1}, X = 1 
Output:

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++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of subsets
// having the given sum
int 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 Code
int 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




// Java implementation of the above approach
import java.util.*;
public class GFG
{
   
// Function to find the count of subsets
// having the given sum
static 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 code
public 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.

Python3




# Python implementation of the above approach
 
# Function to find the count of subsets
# having the given sum
def 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 Code
arr = [1, 1, 1, 1];
N = len(arr)
sum = 1;
 
print(subsetSum(arr, N, sum))
 
# This code is contributed by gfgking.

C#




// C# implementation of the above approach
using System;
 
public class GFG
{
   
// Function to find the count of subsets
// having the given sum
static 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 code
public 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

Javascript




<script>
// Javascript implementation of the above approach
 
// Function to find the count of subsets
// having the given sum
function 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 Code
let 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>
Output
4

Time Complexity: O(N * X)
Auxiliary Space: O(X)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!