Given a non-empty
array 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.
Notice
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example
Given nums = [1, 5, 11, 5]
, return true
two subsets: [1, 5, 5], [11]
Given nums = [1, 2, 3, 9]
, return false
class Solution {
public:
/**
* @param nums a non-empty array only positive integers
* @return return true if can partition or false
*/
bool canPartition(vector<int>& nums) {
// Write your code here
int sum = 0;
for (int i = 0; i< nums.size(); i++)
sum += nums[i];
if (sum % 2)
return false;
int target = sum / 2;
vector<vector<bool>> dp(nums.size() + 1, vector<bool>(target + 1));
for (int i = 0; i <= nums.size(); i++)
{
for (int j = 0; j <= target; j++)
{
dp[i][j] = false;
}
}
for (int i = 0; i <= nums.size(); i++)
dp[i][0] = true;
for (int i = 1; i <= nums.size(); i++)
{
for (int k = 1; k <= target; k++)
{
if (dp[i - 1][k] == true)
{
dp[i][k] = true;
}
if (k - nums[i - 1] >= 0 && dp[i - 1][k - nums[i - 1]] == true)
{
dp[i][k] = true;
}
}
}
return dp[nums.size()][target];
}
};