This reduces to a subset sum problem: can we find a subset that sums to total_sum / 2? We use a 1D boolean DP array where dp[j] indicates whether sum j is achievable.
- If total sum is odd, return False.
- Set target = total_sum // 2.
- Create a boolean
dparray of sizetarget + 1. dp[0] = True.- For each number, iterate from target down to the number:
dp[j] = dp[j] or dp[j - num].
- Return
dp[target].
- Time Complexity: O(N * target).
- Space Complexity: O(target).
def can_partition(nums):
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
dp = [False] * (target + 1)
dp[0] = True
for num in nums:
for j in range(target, num - 1, -1):
dp[j] = dp[j] or dp[j - num]
return dp[target]