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 a 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.
This method is valid for all the integers.
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++
// 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 DPint dp[maxN][maxSum + minSum];bool v[maxN][maxSum + minSum]; // Function to return the required countint 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 codeint main(){ int arr[] = { 3, 3, 3, 3 }; int n = sizeof(arr) / sizeof(int); int x = 6; cout << findCnt(arr, 0, x, n); return 0;} |
Java
// Java implementation of the approachimport 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 DPstatic int [][]dp = new int[maxN][maxSum + minSum];static boolean [][]v = new boolean[maxN][maxSum + minSum]; // Function to return the required countstatic 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 codepublic 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 |
Python3
# Python3 implementation of the approach import numpy as np maxN = 20maxSum = 50minSum = 50base = 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 |
C#
// C# implementation of the approachusing System; class GFG { static int maxN = 20;static int maxSum = 50;static int minSum = 50;static int Base = 50; // To store the states of DPstatic int [,]dp = new int[maxN, maxSum + minSum];static Boolean [,]v = new Boolean[maxN, maxSum + minSum]; // Function to return the required countstatic 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 codepublic 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 |
Javascript
<script> // Javascript implementation of the approach var maxN = 20var maxSum = 50var minSum = 50var base = 50 // To store the states of DPvar dp = Array.from(Array(maxN), ()=>Array(maxSum+minSum));var v = Array.from(Array(maxN), ()=>Array(maxSum+minSum)); // Function to return the required countfunction 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 codevar arr = [3, 3, 3, 3];var n = arr.length;var x = 6;document.write( findCnt(arr, 0, x, n)); </script> |
6
Method 2: Using Tabulation Method:
This method is valid only for those arrays which contains positive elements. In this method we use a 2D array of size (arr.size() + 1) * (target + 1) of type integer. Initialization of Matrix: mat[0][0] = 1 because If the size of sum is
if (A[i] > j) DP[i][j] = DP[i-1][j] else DP[i][j] = DP[i-1][j] + DP[i-1][j-A[i]]
This means that if the current element has a value greater than the ‘current sum value’ we will copy the answer for previous cases
And if the current sum value is greater than the ‘ith’ element we will see if any of the previous states have already experienced the sum=’j’ and any previous states experienced a value ‘j – A[i]’ which will solve our purpose
C++
#include <bits/stdc++.h>using namespace std; int subsetSum(int a[], int n, int sum){ // Initializing the matrix int tab[n + 1][sum + 1]; // Initializing the first value of matrix tab[0][0] = 1; for (int i = 1; i <= sum; i++) tab[0][i] = 0; for (int i = 1; i <= n; i++) tab[i][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { // if the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} int main(){ int n = 4; int a[] = {3,3,3,3}; int sum = 6; cout << (subsetSum(a, n, sum));} |
Java
import java.io.*;import java.lang.*;import java.util.*; class GFG{ static int subsetSum(int a[], int n, int sum){ // Initializing the matrix int tab[][] = new int[n + 1][sum + 1]; // Initializing the first value of matrix tab[0][0] = 1; for(int i = 1; i <= sum; i++) tab[0][i] = 0; for(int i = 1; i <= n; i++) tab[i][0] = 1; for(int i = 1; i <= n; i++) { for(int j = 1; j <= sum; j++) { // If the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} // Driver Codepublic static void main(String[] args){ int n = 4; int a[] = { 3, 3, 3, 3 }; int sum = 6; System.out.print(subsetSum(a, n, sum));}} // This code is contributed by Kingash |
Python3
def subset_sum(a: list, n: int, sum: int): # Initializing the matrix tab = [[0] * (sum + 1) for i in range(n + 1)] for i in range(1, sum + 1): tab[0][i] = 0 for i in range(n+1): # Initializing the first value of matrix tab[i][0] = 1 for i in range(1, n+1): for j in range(1, sum + 1): if a[i-1] <= j: tab[i][j] = tab[i-1][j] + tab[i-1][j-a[i-1]] else: tab[i][j] = tab[i-1][j] return tab[n][sum] if __name__ == '__main__': a = [3, 3, 3, 3] n = 4 sum = 6 print(subset_sum(a, n, sum)) # This code is contributed by Premansh2001. |
C#
using System; class GFG{ static int subsetSum(int []a, int n, int sum){ // Initializing the matrix int [,]tab = new int[n + 1, sum + 1]; // Initializing the first value of matrix tab[0, 0] = 1; for(int i = 1; i <= sum; i++) tab[0, i] = 0; for(int i = 1; i <= n; i++) tab[i, 0] = 1; for(int i = 1; i <= n; i++) { for(int j = 1; j <= sum; j++) { // If the value is greater than the sum if (a[i - 1] > j) tab[i, j] = tab[i - 1, j]; else { tab[i, j] = tab[i - 1, j] + tab[i - 1, j - a[i - 1]]; } } } return tab[n, sum];} // Driver Codepublic static void Main(String[] args){ int n = 4; int []a = { 3, 3, 3, 3 }; int sum = 6; Console.Write(subsetSum(a, n, sum));}} // This code is contributed by shivanisinghss2110 |
6
Time Complexity: O(sum*n), where the sum is the ‘target sum’ and ‘n’ is the size of the array.
Auxiliary Space: O(sum*n), as the size of the 2-D array, is sum*n.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


