Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Let’s say that the array nums can be broken down into two subsets S1 and S2 of equal sums. We can observe the following things
1
2
3
4
5
6
7
// Sum of all the numbers in subset S1 + Sum of all the numbers in subset S2 = Sum of all the numbers in the array
Sum(S1) + Sum(S2) = Sum(nums)
// If Sum(S1) and Sum(S2) is equal
2*Sum(S1) = Sum(nums)
Sum(S1) = Sum(nums)/2
The problem reduces to finding a subset of sum Sum(nums)/2 in the array. If we can find a subset of sum Sum(nums)/2 then we can definitely partition the array into two subsets of equal sums.
Note that I have already explained the solution approach for the Subset Sum 1 - Is there a subset?. So I will directly jump to the code.