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.
问题:
给一个数组,然后判断是否能够分成两段总和一样的两部分。
问题分析:
DFS深度优先遍历,就是加出所有的可能。
class Solution {
public:
bool result;
bool canPartition(vector<int>& nums) {
int len = nums.size();
int sum=0;
sort(nums.begin(), nums.end());
for(int i=0; i<len; i++){
sum += nums[i];
}
vector< bool > flag(len, 0);
helper(nums, sum, 0, flag);
return result;
}
void helper(vector<int>& nums, int sum, int n, vector< bool > &flag){
for(int i=0; i < nums.size() ; i++){
if(flag[i] == 1){
continue;
}
flag[i]=1;
n = n + nums[i];
if(n == sum -n){
result=1;
}
else if(n < sum -n){
helper(nums, sum, n, dp);
}
n = n - nums[i];
flag[i] = 0;
}
}
};
但是这样会超时,因为所有组合太多了,超时是肯定的。
使用动态规划,寻找子问题。
我们想加到一半,设为target,那么,target是最终目的,target如何分呢?
我们寻找另一个target2使得target = target2 + nums[i];这样就将求target转成求target2上,而且问题在缩小,同样target2也可以继续变成一个新的子问题。这样就可以使用动态规划的思想了。
这样我们需要一个数组bool dp[target+1],最基础的值就是nums中的值,是构成target的基础,所以dp[nums[i]]都为1;为了防止重复使用nums[i]对应的dp要依次赋值。
首先使dp[nums[0]]=1;代表nums[0]我们可以取到。再取所有dp[i-nums[0]]的值(nums[0]=<i<=target),而现在所有大于nums[i]的dp值都还是0(未取到);
再使dp[nums[1]]=1;再取所有dp[i-nums[1]]的值,这次取值中我们能发现dp[nums[0] + nums[1]]的值是能取到的。
再对dp[nums[2]]=1;再取所有dp[i-nums[2]]的值,基于前面三个数又多了dp[nums[0] + nums[2]]、dp[nums[1] + nums[2]]、dp[nums[0] + nums[1]+ nums[2]](不超出target的话)
取完所有的值,若target的值能取到(被赋值1)那么就说明能分成相等的两部分。
class Solution {
public:
bool canPartition(vector<int>& nums) {
int len = nums.size();
int sum=0;
for(int i=0; i<len; i++){
sum += nums[i];
}
if(sum & 1){
return false;
}
int target = sum >> 1;
vector< int > dp(target+1, 0);;
dp[0]=1;
for(auto num : nums){
for(int i = target; i>=num; i--){
dp[i] = dp[i] || dp[i-num];
}
}
return dp[target];
}
};
由原来的由大分小的分析,变成由小成大的算法。
动态规划的思维转化,考虑问题的角度从各种组合是否相等的判断a+b+c == c+d+f,到是否存在target值满足target = x + nums[i];x = x + nums[j],再以这种相加且做记录的方式从小至大的方向逼近问题。
然而还有更好的方法。下面我直接用了别人的算法。太厉害了!!!膜拜
其实原理和上个dp一样,bits第一位为1,bits |=bits << n,这样第n位就被标识了1,下次循环来个n1,那么|=就将n,n1,n+n1位的标志位都置为1了,最后相当于加到target,这样运行更加快速,使用内存更小。
class Solution { public: bool canPartition(vector<int>& nums) { bitset<10001> bits(1); int sum = 0; for (auto n : nums) { sum += n; bits |= bits << n; } return !(sum % 2) && bits[sum / 2]; } };