Subset Sum Problem using Backtracking
Problem Statement:
-------------------
Given a set of integers and a target sum, find whether there exists a subset whose
sum is equal to the target sum.
Algorithm (Pseudocode):
------------------------
Function SubsetSum(arr, n, target_sum):
Call backtrack(0, 0)
Function backtrack(index, current_sum):
if current_sum == target_sum:
return True
if index == n or current_sum > target_sum:
return False
// Choice 1: Include arr[index] in the subset
if backtrack(index + 1, current_sum + arr[index]):
return True
// Choice 2: Exclude arr[index] from the subset
if backtrack(index + 1, current_sum):
return True
return False
Example:
---------
Input:
- Array = [3, 34, 4, 12, 5, 2]
- Target Sum = 9
Execution Steps:
- Start from index = 0, current_sum = 0
- Include 3 → current_sum = 3
- Exclude 34
- Include 4 → current_sum = 7
- Exclude 12
- Exclude 5
- Include 2 → current_sum = 9 → FOUND
Subset: [3, 4, 2]
Search Tree (Partial):
----------------------
(0,0)
/ \
include 3 (1,3) exclude 3 (1,0)
/ \
include 34 (2,37) exclude 34 (2,3)
X / \
(too big)...
Where (index, current_sum)
X = dead-end
Time and Space Complexity:
---------------------------
- Time Complexity: O(2^n) (Exponential, tries all subsets)
- Space Complexity: O(n) (Recursion depth)
Summary:
---------
Aspect | Value
--------------------|----------------------
Time Complexity | O(2^n)
Space Complexity | O(n)
Type | Exponential, Backtracking
Important | Prune when sum > target