def subset_sum(nums, target):
"""
Determines if there exists a subset of nums that sums to target using dynamic programming.
Args:
nums (list[int]): List of non-negative integers.
target (int): The target sum.
Returns:
bool: True if a subset sums to target, False otherwise.
Time Complexity: O(n * target), where n is len(nums).
Space Complexity: O(target).
Example:
>>> subset_sum([3, 34, 4, 12, 5, 2], 9)
True # Subset: [4, 5]
>>> subset_sum([3, 34, 4, 12, 5, 2], 30)
False
"""
if target < 0:
return False
if target == 0:
return True
n = len(nums)
# dp[j] is True if sum j can be achieved with the nums considered so far
dp = [False] * (target + 1)
dp[0] = True # Empty subset sums to 0
for num in nums:
# Iterate backwards to avoid using the same num multiple times
for j in range(target, num - 1, -1):
if dp[j - num]:
dp[j] = True
return dp[target]
Explanation
DP Table: dp[j] is True if there is a subset of the numbers (processed so far) that sums exactly to j.
Initialization: dp[0] = True because the empty subset sums to 0.
Filling the Table:
For each number num in nums:
Update dp[j] for j from target down to num (backwards iteration prevents reusing the current num).
dp[j] = dp[j] OR dp[j - num] (include num or not).
Result: dp[target] gives the answer.
This is the standard 0/1 knapsack-style DP for the subset sum problem, optimized to O(target) space. It assumes non-negative integers in nums; negative numbers would require modifications.