Difficulty: Medium
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.
思路分析:
动态规划算法,f[i][j]表示前i个数能否取出和为j的方案
状态转移方程 f[i][j]=f[i-1][j] || f[i-1][ j-nums[i] ];
如果j从sum到nums[i]递减遍历,那么状态转移方程简写为 f[j]=f[j] || f[ j-nums[i] ];
时间复杂度为O(n*sum),sum为nums[i]所有元素之和
class Solution {
public:
bool canPartition(vector<int>& nums) {
bool f[10005];
int sum,n;
n=nums.size();
sum=0;
for(int i=0;i<n;i++)
{
sum+=nums[i];
}
if(sum%2) return false;
sum=sum/2;
for(int i=1;i<=sum;i++)
f[i]=false;
f[0]=true;
for(int i=0;i<n;i++)
for(int j=sum;j>=nums[i];j--)
f[j] = f[j] || f[j-nums[i] ];
return f[sum];
}
};

本文探讨了如何使用动态规划解决背包问题的一个特定实例——将数组分割成两个子集,使得两个子集的元素之和相等。通过具体的例子说明了算法的实现过程,并提供了完整的C++代码。

951

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



