【LeetCode】416. Partition Equal Subset Sum

416. Partition Equal Subset Sum

Description:
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.
Difficulty:Medium

Example:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].
方法1:转化问题,动态规划
  • Time complexity : O ( n ∗ s u m ) O\left ( n * sum \right ) O(nsum)
  • Space complexity : O ( s u m / 2 ) O\left ( sum/2 \right ) O(sum/2)
    思路
    因为先做了494. Target Sum 这道题目,所以自然而然想到这道题目可以转化为添加正负号使得sum为0,再接着转化就是在nums中找到一个集合,使得这个集合的和为sum/2
    由于这种思维惯性,导致了运算操作冗余,其实没必要计算出来有几种组合方式,只需要记录是否有这种组合即可,具体代码请看方法2。
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if(sum % 2 == 1) return false;
        int s = sum / 2;
        vector<double> dp(s+1); //这里用了double是因为需要记录的次数实在太大,只能用double,所以这个方法不可取
        dp[0] = 1;
        for( auto num : nums)
            for(int i = s;i >= num; i--)
                dp[i] += dp[i-num];
        return dp[s] > 0 ? true : false;
    }
};
方法2:转化问题,动态规划
  • Time complexity : O ( n ) O\left ( n\right ) O(n)
  • Space complexity : O ( s u m ) O\left ( sum \right ) O(sum)
    思路:因为只需要记录是否存在这种可能,所以用bitset即可。
    遍历数组,每次将bits向左移num位,并且与自己与,因为num的加入,bits的某些位发生了变化,保持了累加性。说的比较难懂,来点例子。
核心代码:bits |= bits << num;
nums = [1, 1, 2, 2]
bits = 0000001
-->1 bits = 0000011
-->1 bits = 0000111
-->2 bits = 0011111
-->2 bits = 1111111
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        bitset<10001> bits(1);
        for(auto num : nums)
            bits |= bits << num;
        return !(sum & 1) && bits[sum / 2];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值