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.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
Solution : (Recursion)
class Solution
{
public:
bool subsetSum(vector<int> v, int sum, int pos)
{
if(pos == v.size()){
return false;
}
if (sum == 0)
{
return true;
}
if (subsetSum(v, sum - v[pos], pos + 1) || subsetSum(v, sum, pos + 1))
{
return true;
}
return false;
}
bool canPartition(vector<int> &nums)
{
int s = 0;
for (int i = 0; i < nums.size(); i++)
{
s = s + nums[i];
}
// Checking if solution exits
if (s % 2 == 0)
{
//Subset sum(Finding a subset with given sum)
if (subsetSum(nums, s / 2, 0))
{
return true;
}
return false;
}
return false;
}
};
Time Complexity: O(2^n)
Solution : (DP)
class Solution
{
public:
bool subsetSum(vector<int> nums, int target)
{
vector<vector<bool>> v(nums.size() + 1, vector<bool>(target + 1, 0));
v[0][0] = true;
for (int i = 1; i <= nums.size(); i++)
{
int cur = nums[i - 1];
for (int j = 0; j <= target; j++)
{
if (j < cur)
{
v[i][j] = v[i - 1][j];
}
else
{
v[i][j] = v[i - 1][j] || v[i - 1][j - cur];
}
}
}
return v[nums.size()][target];
}
bool canPartition(vector<int> &nums)
{
int s = 0;
for (int i = 0; i < nums.size(); i++)
{
s = s + nums[i];
}
if (s % 2 == 0)
{
//Subset sum(Finding a subset with given sum)
if (subsetSum(nums, s / 2))
{
return true;
}
return false;
}
return false;
}
};
Time Complexity: O(n * m)
Space Complexity: O(n * m)