Count of subsets with sum equal to X

Given an array arr[] of length N and an integer X, the task is to find the number of subsets with sum equal to X.

Examples:

Input: arr[] = {1, 2, 3, 3}, X = 6
Output: 3
All the possible subsets are {1, 2, 3},
{1, 2, 3} and {3, 3}



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

Approach: A simple approach is to solve this problem by generating all the possible subsets and then checking whether the subset has the required sum. This approach will have exponential time complexity. However, for smaller values of X and array elements, this problem can be solved using dynamic programming.
Let’s look at the recurrence relation first.

dp[i][C] = dp[i + 1][C – arr[i]] + dp[i + 1][C]

Let’s understand the states of the DP now. Here, dp[i][C] stores the number of subsets of the sub-array arr[i…N-1] such that their sum is equal to C.
Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
#define maxN 20
#define maxSum 50
#define minSum 50
#define base 50
  
// To store the states of DP
int dp[maxN][maxSum + minSum];
bool v[maxN][maxSum + minSum];
  
// Function to return the required count
int findCnt(int* arr, int i, int required_sum, int n)
{
    // Base case
    if (i == n) {
        if (required_sum == 0)
            return 1;
        else
            return 0;
    }
  
    // If the state has been solved before
    // return the value of the state
    if (v[i][required_sum + base])
        return dp[i][required_sum + base];
  
    // Setting the state as solved
    v[i][required_sum + base] = 1;
  
    // Recurrence relation
    dp[i][required_sum + base]
        = findCnt(arr, i + 1, required_sum, n)
          + findCnt(arr, i + 1, required_sum - arr[i], n);
    return dp[i][required_sum + base];
}
  
// Driver code
int main()
{
    int arr[] = { 3, 3, 3, 3 };
    int n = sizeof(arr) / sizeof(int);
    int x = 6;
  
    cout << findCnt(arr, 0, x, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG 
{
static int maxN = 20;
static int maxSum = 50;
static int minSum = 50;
static int base = 50;
  
// To store the states of DP
static int [][]dp = new int[maxN][maxSum + minSum];
static boolean [][]v = new boolean[maxN][maxSum + minSum];
  
// Function to return the required count
static int findCnt(int []arr, int i, 
                   int required_sum, int n)
{
    // Base case
    if (i == n) 
    {
        if (required_sum == 0)
            return 1;
        else
            return 0;
    }
  
    // If the state has been solved before
    // return the value of the state
    if (v[i][required_sum + base])
        return dp[i][required_sum + base];
  
    // Setting the state as solved
    v[i][required_sum + base] = true;
  
    // Recurrence relation
    dp[i][required_sum + base] = 
          findCnt(arr, i + 1, required_sum, n) + 
          findCnt(arr, i + 1, required_sum - arr[i], n);
    return dp[i][required_sum + base];
}
  
// Driver code
public static void main(String []args) 
{
    int arr[] = { 3, 3, 3, 3 };
    int n = arr.length;
    int x = 6;
  
    System.out.println(findCnt(arr, 0, x, n));
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
import numpy as np
  
maxN = 20
maxSum = 50
minSum = 50
base = 50
  
# To store the states of DP 
dp = np.zeros((maxN, maxSum + minSum)); 
v = np.zeros((maxN, maxSum + minSum)); 
  
# Function to return the required count 
def findCnt(arr, i, required_sum, n) :
  
    # Base case 
    if (i == n) :
        if (required_sum == 0) :
            return 1
        else :
            return 0
  
    # If the state has been solved before 
    # return the value of the state 
    if (v[i][required_sum + base]) :
        return dp[i][required_sum + base]; 
  
    # Setting the state as solved 
    v[i][required_sum + base] = 1
  
    # Recurrence relation 
    dp[i][required_sum + base] = findCnt(arr, i + 1
                                         required_sum, n) + \
                                 findCnt(arr, i + 1
                                         required_sum - arr[i], n); 
      
    return dp[i][required_sum + base]; 
  
# Driver code 
if __name__ == "__main__"
  
    arr = [ 3, 3, 3, 3 ]; 
    n = len(arr); 
    x = 6
  
    print(findCnt(arr, 0, x, n)); 
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
      
class GFG 
{
  
static int maxN = 20;
static int maxSum = 50;
static int minSum = 50;
static int Base = 50;
  
// To store the states of DP
static int [,]dp = new int[maxN, maxSum + minSum];
static Boolean [,]v = new Boolean[maxN, maxSum + minSum];
  
// Function to return the required count
static int findCnt(int []arr, int i, 
                   int required_sum, int n)
{
    // Base case
    if (i == n) 
    {
        if (required_sum == 0)
            return 1;
        else
            return 0;
    }
  
    // If the state has been solved before
    // return the value of the state
    if (v[i, required_sum + Base])
        return dp[i, required_sum + Base];
  
    // Setting the state as solved
    v[i, required_sum + Base] = true;
  
    // Recurrence relation
    dp[i, required_sum + Base] = 
          findCnt(arr, i + 1, required_sum, n) + 
          findCnt(arr, i + 1, required_sum - arr[i], n);
    return dp[i,required_sum + Base];
}
  
// Driver code
public static void Main(String []args) 
{
    int []arr = { 3, 3, 3, 3 };
    int n = arr.Length;
    int x = 6;
  
    Console.WriteLine(findCnt(arr, 0, x, n));
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

6


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01, 29AjayKumar