Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Subset Sum Problem
In this article, we will learn how to solve the Subset Sum Problem using Python. This is a classic computer science problem where we need to determine if there exists a subset of given numbers that adds up to a target sum.
Problem Statement: Given a set of non-negative integers and a target sum, determine if there exists a subset of the given set with a sum equal to the target sum.
Naive Recursive Approach
The recursive approach explores all possible subsets by either including or excluding each element ?
def subset_sum_recursive(numbers, n, target_sum):
# Base Cases
if target_sum == 0:
return True
if n == 0 and target_sum != 0:
return False
# Ignore if last element is greater than sum
if numbers[n - 1] > target_sum:
return subset_sum_recursive(numbers, n - 1, target_sum)
# Check sum by:
# (1) including the last element
# (2) excluding the last element
return (subset_sum_recursive(numbers, n - 1, target_sum) or
subset_sum_recursive(numbers, n - 1, target_sum - numbers[n - 1]))
# Test the function
numbers = [2, 14, 6, 22, 4, 8]
target_sum = 10
n = len(numbers)
if subset_sum_recursive(numbers, n, target_sum):
print("Found a subset with given sum")
else:
print("No subset with given sum")
Found a subset with given sum
Dynamic Programming Approach
The DP approach uses a 2D table to store results and avoid redundant calculations, making it more efficient ?
def subset_sum_dp(numbers, target_sum):
n = len(numbers)
# Create a DP table
# dp[i][j] represents whether sum j can be obtained with first i elements
dp = [[False for _ in range(target_sum + 1)] for _ in range(n + 1)]
# Base case: sum 0 can always be obtained with empty subset
for i in range(n + 1):
dp[i][0] = True
# Fill the DP table
for i in range(1, n + 1):
for j in range(1, target_sum + 1):
if j < numbers[i - 1]:
# Current number is larger than target sum
dp[i][j] = dp[i - 1][j]
else:
# Either include current number or exclude it
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - numbers[i - 1]]
return dp[n][target_sum]
# Test the function
numbers = [2, 14, 6, 22, 4, 8]
target_sum = 10
if subset_sum_dp(numbers, target_sum):
print("Found a subset with given sum")
# Find and print one such subset
def find_subset(numbers, target_sum):
n = len(numbers)
dp = [[False for _ in range(target_sum + 1)] for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = True
for i in range(1, n + 1):
for j in range(1, target_sum + 1):
if j < numbers[i - 1]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - numbers[i - 1]]
# Backtrack to find the subset
subset = []
i, j = n, target_sum
while i > 0 and j > 0:
if dp[i - 1][j]:
i -= 1
else:
subset.append(numbers[i - 1])
j -= numbers[i - 1]
i -= 1
return subset
result_subset = find_subset(numbers, target_sum)
print(f"One such subset: {result_subset}")
print(f"Sum: {sum(result_subset)}")
else:
print("No subset with given sum")
Found a subset with given sum One such subset: [2, 8] Sum: 10
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(2^n) | O(n) | Small datasets, educational purposes |
| Dynamic Programming | O(n × sum) | O(n × sum) | Larger datasets, practical applications |
Conclusion
The Subset Sum Problem can be solved using recursive or dynamic programming approaches. While recursion is simpler to understand, DP is more efficient for larger inputs, reducing time complexity from exponential to polynomial.
