VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subsets-with-sum-equal-to-x-using-recursion/

⇱ Count of subsets with sum equal to target using Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of subsets with sum equal to target using Recursion

Last Updated : 12 Jul, 2025

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

Examples:

Input: arr[] = [1, 2, 3, 3], target = 6 
Output:
Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3]

Input: arr[] = [1, 1, 1, 1], target = 1 
Output:
Explanation: All the possible subsets are [1], [1], [1] and [1]

Approach:

We can identify a recursive pattern in this problem. There are two state variables:

  1. The current index i in the array arr[].
  2. The cumulative sum currentSum of the subsets being considered.

We consider two cases for recursion:

Exclude the current element: The current element is not included in the subset, and the sum remains unchanged. This corresponds to:

  • countSubsets(i + 1, currentSum, target).

Include the current element: The current element is included in the subset, and the sum is updated as currentSum + arr[i]. This corresponds to:

  • countSubsets(i + 1, currentSum + arr[i], target)

Recurrence relation:

  • countSubsets(i, currentSum, target) = countSubsets(i+1, currentSum, target) + countSubsets(i+1, currentSum + arr[i], target)​

Base Case: If i == n (all elements have been processed), return 1 if the currentSumequal to target else 0.


Output
3

Time Complexity: O(2^n), where n is the size of array.
Auxiliary Space: O(n)

Please refer to efficient method to solve the problem using Dynamic Programming.

Comment
Article Tags: