VOOZH about

URL: https://www.geeksforgeeks.org/dsa/combinational-sum/

⇱ Target Sum Combinations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Target Sum Combinations

Last Updated : 3 Oct, 2025

Given an array arr[] of distinct integers and an integer target, find all unique combinations of array where the sum of chosen element is equal to target. The same element may be chosen any number of times to make target.

Examples: 

Input: arr[] = [1, 2, 3], target = 5
Output: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [2, 3]]
Explanation: All the combination have sum of elements equals to target.

Input: arr[] = [2, 4], target = 1
Output: []
Explanation: No combination exits whose sum is equals to target

[Approach] Using Recursion and Backtracking

The idea is to explore all possible combinations of numbers that add up to the target. For each element, we reduce the target by its value and continue the process recursively. If at any point the target becomes zero, it means we have found a valid combination. On the other hand, if the target goes negative, we backtrack and discard that path. This way, recursion combined with backtracking helps us systematically generate all valid combinations without missing any possibilities.

Pseudo-code Idea

Base cases:

  • If target < 0 : not a valid combination so return back.
  • If target == 0 : valid combination so store it as an answer.

Recursive choices:
At each step, we have two options:

  • Pick the current element, reduce the target by arr[i] and call recursion with (i, target - arr[i]). Keeping the index unchanged allows us to reuse the current element until the target is either reached or exceeded.
  • Skip the current element, move to the next index and call recursion with (i+1, target).

Output
1 1 1 1 1 
1 1 1 2 
1 1 3 
1 2 2 
2 3 

Time Complexity: O(n^(T/M)), where n is the number of candidates, T is the target, and M is the smallest candidate.

Backtracking can be visualized as a DFS on an n-ary tree:

  • Each node represents a choice of candidate, so it can have at most n children.
  • The maximum depth is roughly T / M, because in the worst case we keep adding the smallest candidate until reaching the target.
  • The total number of nodes in an n-ary tree of depth T/M is bounded by n^(T/M), giving the loose upper bound.

Auxiliary Space: O(T / M), because the recursion stack can go as deep as the maximum number of elements in a combination (adding the smallest candidate repeatedly).

Comment