Count of subsets with sum equal to X using Recursion

21 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 using recursion.Examples:  
Input: arr[] = {2, 3, 5, 6, 8, 10}, X = 10 Output: 3 Explanation: All possible subsets with sum 10 are {2, 3, 5}, {2, 8}, {10}Input: arr[] = {1, 2, 3, 4, 5}, X = 7 Output: 3 Explanation: All possible subsets with sum 7 are {2, 5}, {3, 4}, {1, 2, 4}  
 
Approach: The idea is to recursively check all the subsets. If any subset has the sum equal to N, then increment the count by 1. Else, continue. In order to form a subset, there are two cases for every element:  
Include the element in the set.
Exclude the element in the set.
Therefore, the following steps can be followed to compute the answer:  
Get the array for which the subsets with the sum equal to K is to be found.Recursively count the subsets with the sum equal to K in the following way:Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition.
Get the array for which the subsets with the sum equal to K is to be found.
Recursively count the subsets with the sum equal to K in the following way:Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition.
Base Case: The base case will be when the end of the array has been reached. If here the sum has been found as X, then increase the count of the subset by 1. Return the count evaluated in the base condition.
if (n == 0) {
    if (sum == s)
        count++;
    return count;
}
Recursive Call: If the base case is not satisfied, then call the function twice. Once by including the element at index ‘i’ and once by not including the element. Find the count for both these cases and then return the final count.
count = subsetSum(arr, n, sum , s , count);
count = subsetSum(arr, n, sum, s + arr[n-1 count);
Return Statement: At every step, the count of subsets by either including a particular element or not including a particular element is returned. Finally, when the entire recursion stack is executed, the total count is returned.
From the above approach, it can be clearly analyzed that if there are N elements in the array, then a total of 2N cases arise. Every element in the array is checked for the above cases using recursion. Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to print the count of// subsets with sum equal to the given value X #include <iostream>using namespace std; // Recursive function to return the count// of subsets with sum equal to the given valueint subsetSum(int arr[], int n, int i,              int sum, int count){    // The recursion is stopped at N-th level    // where all the subsets of the given array    // have been checked    if (i == n) {         // Incrementing the count if sum is        // equal to 0 and returning the count        if (sum == 0) {            count++;        }        return count;    }     // Recursively calling the function for two cases    // Either the element can be counted in the subset    // If the element is counted, then the remaining sum    // to be checked is sum - the selected element    // If the element is not included, then the remaining sum    // to be checked is the total sum    count = subsetSum(arr, n, i + 1, sum - arr[i], count);    count = subsetSum(arr, n, i + 1, sum, count);    return count;} // Driver codeint main(){    int arr[] = { 1, 2, 3, 4, 5 };    int sum = 10;    int n = sizeof(arr) / sizeof(arr[0]);     cout << subsetSum(arr, n, 0, sum, 0);}
// Java program to print the count of// subsets with sum equal to the given value Ximport java.util.*; class GFG {     // Recursive function to return the count    // of subsets with sum equal to the given value    static int subsetSum(int arr[], int n, int sum, int s,                         int count)    {               // The recursion is stopped at N-th level        // where all the subsets of the given array        // have been checked        if (n == 0) {             // Incrementing the count if sum is            // equal to the subset and returning the count            if (sum == s) {                count++;            }            return count;        }         count = subsetSum(arr, n - 1, sum, s, count);        count = subsetSum(arr, n - 1, sum, s + arr[n - 1],                          count);        return count;    }     // Driver code    public static void main(String[] args)    {        int arr[] = { 1, 2, 3, 4, 5 };        int sum = 10;        int s = 0; // Initially assigning the sum of subset                   // to be zero        int n = arr.length;         System.out.print(subsetSum(arr, n, sum, s, 0));    }} // This code is contributed by Sparsh Choudhary// (sparsht123t)
# Python3 program to print the count of# subsets with sum equal to the given value X # Recursive function to return the count# of subsets with sum equal to the given valuedef subsetSum(arr, n, i,sum, count):         # The recursion is stopped at N-th level    # where all the subsets of the given array    # have been checked    if (i == n):         # Incrementing the count if sum is        # equal to 0 and returning the count        if (sum == 0):            count += 1        return count     # Recursively calling the function for two cases    # Either the element can be counted in the subset    # If the element is counted, then the remaining sum    # to be checked is sum - the selected element    # If the element is not included, then the remaining sum    # to be checked is the total sum    count = subsetSum(arr, n, i + 1, sum - arr[i], count)    count = subsetSum(arr, n, i + 1, sum, count)    return count # Driver codearr = [1, 2, 3, 4, 5]sum = 10n = len(arr) print(subsetSum(arr, n, 0, sum, 0)) # This code is contributed by mohit kumar 29
// C# program to print the count of// subsets with sum equal to the given value Xusing System; class GFG{ // Recursive function to return the count// of subsets with sum equal to the given valuestatic int subsetSum(int []arr, int n, int i,                    int sum, int count){    // The recursion is stopped at N-th level    // where all the subsets of the given array    // have been checked    if (i == n)    {         // Incrementing the count if sum is        // equal to 0 and returning the count        if (sum == 0)        {            count++;        }        return count;    }     // Recursively calling the function for two cases    // Either the element can be counted in the subset    // If the element is counted, then the remaining sum    // to be checked is sum - the selected element    // If the element is not included, then the remaining sum    // to be checked is the total sum    count = subsetSum(arr, n, i + 1, sum - arr[i], count);    count = subsetSum(arr, n, i + 1, sum, count);    return count;} // Driver codepublic static void Main(String[] args){    int []arr = { 1, 2, 3, 4, 5 };    int sum = 10;    int n = arr.Length;     Console.Write(subsetSum(arr, n, 0, sum, 0));}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to print the count of// subsets with sum equal to the given value X // Recursive function to return the count// of subsets with sum equal to the given valuefunction subsetSum(arr, n, i, sum, count){    // The recursion is stopped at N-th level    // where all the subsets of the given array    // have been checked    if (i == n) {         // Incrementing the count if sum is        // equal to 0 and returning the count        if (sum == 0) {            count++;        }        return count;    }     // Recursively calling the function for two cases    // Either the element can be counted in the subset    // If the element is counted, then the remaining sum    // to be checked is sum - the selected element    // If the element is not included, then the remaining sum    // to be checked is the total sum    count = subsetSum(arr, n, i + 1, sum - arr[i], count);    count = subsetSum(arr, n, i + 1, sum, count);    return count;} // Driver codevar arr = [1, 2, 3, 4, 5];var sum = 10;var n = arr.length;document.write( subsetSum(arr, n, 0, sum, 0)); </script>
3
 
Time Complexity: O(n2)
Auxiliary Space: O(n2)
Efficient Approach: An efficient method to solve the problem using Dynamic Programming has been discussed in this article. 
mohit kumar 29
29AjayKumar
princiraj1992
Satzy
Code_Mech
itsok
sparsht123t
vansikasharma1329
subset
Arrays
Mathematical
Recursion
Arrays
Mathematical
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
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7