VOOZH about

URL: https://www.geeksforgeeks.org/dsa/subset-sum-problem/

⇱ Subset Sum Problem using Backtracking - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subset Sum Problem using Backtracking

Last Updated : 14 Nov, 2025

Given a set[] of non-negative integers and a value sum, the task is to print the subset of the given set whose sum is equal to the given sum.

Examples:

Input: set[] = {1,2,1}, sum = 3
Output: [1,2],[2,1]
Explanation: There are subsets [1,2],[2,1] with sum 3.

Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 30
Output: []
Explanation: There is no subset that add up to 30.

Subset sum can also be thought of as a special case of the 0–1 Knapsack problem. For each item, there are two possibilities:

  • Include the current element in the subset and recur for the remaining elements with the remaining Sum.
  • Exclude the current element from the subset and recur for the remaining elements.

Finally, if Sum becomes 0 then print the elements of current subset. The recursion’s base case would be when no items are left, or the sum becomes negative, then simply return.

👁 subset_Sum_Final

Implementation of the above approach:

Output 1:
[ 2 1 ][ 1 2 ]
Output 2:
There is no such subset

Complexity analysis:

  • Time Complexity: O(2n) The above solution may try all subsets of the given set in the worst case. Therefore time complexity of the above solution is exponential.
  • Auxiliary Space: O(n) where n is recursion stack space.
Comment