Examining Problem Definition
I'm currently focused on defining the core elements of the Subset Sum Problem. The inputs, specifically a set of non-negative integers and a target sum, are clear. I'm now clarifying the expected output: a simple boolean indicating whether a subset exists that sums up to the target. This foundational clarity is crucial for constructing a dynamic programming solution.
Refining DP State Definition
I'm now refining the DP state to align with the recurrence relation's logic. Thinking through the edge cases, specifically when the target sum is zero (easily achievable with an empty subset). Additionally, the initial state of the dp table is being considered to clarify how it should be initiated with the base cases.
Evaluating Table Implementation
I'm now implementing the 2D matrix, focusing on the core logic: the recurrence relation dp[i][j] = dp[i-1][j] OR dp[i-1][j - arr[i-1]]. I'm working through a small example set to verify that the table is being built correctly, and I am double checking how the array indices map to the problem. I need to make sure I am handling the indices correctly.
Developing Code Implementation
The code's structure and overall flow are coming into focus. I'm starting by translating the 2D matrix algorithm into Python, ensuring the base cases and recurrence relation are correctly encoded. After verifying its correctness, I will shift my focus to the optimized 1D version. I'm ensuring all edge cases are addressed.
Formulating the Solution
I'm now implementing the 1D space optimization, carefully stepping through the backward iteration of the target sum. I'm checking that array indexing remains consistent. After verifying, I plan on wrapping it up with a concise explanation.
Here is a complete solution for the Subset Sum Problem.
I will provide two versions:
- Standard 2D Matrix Approach: Easier to understand logically.
- Space Optimized 1D Approach: The most efficient implementation (Standard for competitive programming/production).
The Logic (Dynamic Programming)
The core idea is to build a truth table. Let's say we have a target sum S and an array of numbers.
We define a state dp[i][j] where:
i represents that we are considering the first i items in the array.
j represents the target sum from 0 to S.
- The value is
True if we can make sum j using a subset of the first i items, and False otherwise.
The Recurrence Relation:
For every number in the array, we have two choices:
- Exclude it: The possibility remains the same as it was for the previous set of items (
dp[i-1][j]).
- Include it: We check if the sum
j - current_number was possible using previous items (dp[i-1][j - current_number]).
Solution 1: Space Optimized (Recommended)
Since we only really need the results from the "previous row" to calculate the "current row," we can compress the 2D matrix into a single 1D array.
Note on looping: We must iterate through the target sum backwards. If we iterate forwards, we risk using the current number multiple times for the same sum.
def subset_sum_optimized(numbers, target):
"""
Determines if a subset of 'numbers' adds up to 'target'
using O(target) space.
"""
# Initialize DP array
# dp[j] will be True if sum 'j' is possible
dp = [False] * (target + 1)
# Base Case: A sum of 0 is always possible (by choosing no elements)
dp[0] = True
# Iterate through each number in the input array
for num in numbers:
# Update the dp array for all sums that can be formed including 'num'
# We traverse backwards from target down to num
for current_sum in range(target, num - 1, -1):
if dp[current_sum - num] is True:
dp[current_sum] = True
return dp[target]
# --- Example Usage ---
arr = [3, 34, 4, 12, 5, 2]
tgt = 9
result = subset_sum_optimized(arr, tgt)
print(f"Input: {arr}")
print(f"Target: {tgt}")
print(f"Subset exists: {result}")
Solution 2: Standard 2D Matrix (For Educational Purposes)
If you need to reconstruct the actual subset later or visualize the process, the 2D table is better.
def subset_sum_2d(numbers, target):
n = len(numbers)
# Create a matrix (n+1) x (target+1)
# dp[i][j] = True if sum 'j' can be achieved using first 'i' items
dp = [[False for _ in range(target + 1)] for _ in range(n + 1)]
# Base Case: Sum 0 is always possible (empty set)
for i in range(n + 1):
dp[i][0] = True
# Fill the DP table
for i in range(1, n + 1):
current_num = numbers[i-1]
for j in range(1, target + 1):
# If current number is greater than sum j, we can't include it
if current_num > j:
dp[i][j] = dp[i-1][j]
else:
# Choice 1: Exclude current_num -> dp[i-1][j]
# Choice 2: Include current_num -> dp[i-1][j - current_num]
dp[i][j] = dp[i-1][j] or dp[i-1][j - current_num]
return dp[n][target]
Complexity Analysis
Assuming N is the number of elements and M is the target sum:
- Time Complexity: O(N⋅M)
- We iterate through every number (N) and for each number, we iterate through the target sums (M). This is pseudo-polynomial. If M is very large (e.g., ), this algorithm is slow.