416. Partition Equal Subset Sum子数组和问题

相同子集和分割。

与0-1背包相似:01背包(1)01背包(2)

问题:

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:
Both the array size and each of the array element will not exceed 100.

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.
 
以下内容参见:http://www.cnblogs.com/grandyang/p/5951422.html


这道题给了我们一个数组,问我们这个数组能不能分成两个非空子集合,使得两个子集合的元素之和相同。那么我们想,原数组所有数字和一定是偶数,不然根本无法拆成两个和相同的子集合,那么我们只需要算出原数组的数字之和,然后除以2,就是我们的target,那么问题就转换为能不能找到一个非空子集合,使得其数字之和为target。开始我想的是遍历所有子集合,算和,但是这种方法无法通过OJ的大数据集合。于是乎,动态规划DP就是我们的不二之选。我们定义一个一维的dp数组,其中dp[i]表示数字i是否是原数组的任意个子集合之和,那么我们我们最后只需要返回dp[target]就行了。我们初始化dp[0]为true,由于题目中限制了所有数字为正数,那么我们就不用担心会出现和为0或者负数的情况。那么关键问题就是要找出递归公式了,我们需要遍历原数组中的数字,对于遍历到的每个数字nums[i],我们需要更新我们的dp数组,要更新[nums[i], target]之间的值,那么对于这个区间中的任意一个数字j,如果dp[j - nums[j]]为true的话,那么dp[j]就一定为true,于是地推公式如下:


dp[j] = dp[j] || dp[j - nums[i]]         (nums[i] <= j <= target,要倒序来算)


例如:1  5  3

              index:   0   1   2   3   4   5   6   7   8   9

     加入1时{1}:   1    1                                              {1}时,得到2个不同的和

   加入5时{1,5}:  1    1                 1   1                       来了5之后,在原来的基础上,多了5和6,共4个不同的和

加入3时{1,5,3}:  1    1        1   1   1   1       1   1         加入3之后,由原来的4个和变成8个和。


这个dp过程是:{1} -> {1,5} -> {1,5,3} ,每次计算,我们都要利用前一个状态的计算结果(例如,计算{1,5,3}时,需要用到{1,5}的结果,而{1,5}的结果已经计算好并保存在dp[target+1]中),这正是dp中关键的思想。


有了递推公式,那么我们就可以写出代码如下:

//dp
bool canPartition(int* nums, int numsSize) {
    int sum = 0, ret;
    for(int i = 0; i < numsSize; ++i) sum += nums[i];
    if(sum%2) return false;
    int target = sum/2;
    bool* dp = (bool*)malloc((target+1)*sizeof(bool));
    memset(dp, 0, (target+1)*sizeof(bool));
    dp[0] = 1;
    for(int i = 0; i < numsSize; ++i)
        for(int j = target; j >= nums[i]; --j)
            dp[j] = dp[j]|dp[j-nums[i]];
    ret = dp[target];
    free(dp);
    return ret;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值