Problem
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Algorithm
Dynamics Programming (DP). Sum all the number and find if there are subset that the sum can get the half of the total sum.
Use DP to find if the value can be formed.
Code
class Solution:
def canPartition(self, nums: List[int]) -> bool:
sum_n = 0
for num in nums:
sum_n += num
if sum_n % 2 == 1:
return False
half = sum_n // 2
visit = [0] * (half + 1)
visit[0] = 1
for num in nums:
for v in range(half, num-1, -1):
if visit[v - num]:
visit[v] = 1
return visit[half] == 1