题目:
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.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
分析:这道题是要我们判断一个数组是否可以分成和相等的两部分。这道题可以看成不重复的背包问题。先算出n个数的和sum,然后假设背包容量为sum/2.将每个数看成价值和大小都为数字的大小的物品,若n个物体能刚好填满整个背包,则表示该数组可以分成和相等的两部分。
若sum不是偶数,则不可能分成和相等的两部分,可直接返回false。
代码:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for(int i = 0;i<nums.size();i++)
sum+=nums[i];
if(sum%2!=0) return false;
int *dp;
dp = new int [sum/2+1];
for(int i = 0;i<=sum/2;i++)
{
if(i<nums[0]) dp[i] = 0;
else
dp[i] = nums[0];
}
for(int i = 1;i<nums.size();i++)
{
for(int j = sum/2;j>=nums[i];j--)
{
dp[j] =max(dp[j],dp[j-nums[i]]+nums[i]);
}
}
if(dp[sum/2] == sum/2)
return true;
else return false;
}
};
本文探讨了如何判断一个仅包含正整数的数组能否被划分为两个子集,使得这两个子集的元素之和相等。通过将其视为一种特定类型的背包问题来解决,并提供了一种基于动态规划的方法。
417

被折叠的 条评论
为什么被折叠?



