416. Partition Equal Subset Sum

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:

  1. Each of the array element will not exceed 100.
  2. 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];
    }
};




                
`list.partition()` 和 `set.partition()` 是两种不同的方法,用于不同的数据类型。 `list.partition()` 是 Python 内置的列表方法,它接受一个谓词函数作为参数,并将列表拆分为两个部分:满足谓词函数的元素和不满足谓词函数的元素。它返回一个元组,其中第一个元素是满足谓词函数的元素列表,第二个元素是不满足谓词函数的元素列表,第三个元素是剩余的元素列表(如果有的话)。 例如,假设我们有一个整数列表 `[1, 2, 3, 4, 5, 6]`,我们想要将它们分为奇数和偶数两部分,可以使用 `list.partition()` 方法: ```python nums = [1, 2, 3, 4, 5, 6] odd, even, rest = nums.partition(lambda x: x % 2 != 0) print(odd) # [1, 3, 5] print(even) # [2, 4, 6] print(rest) # [] ``` `set.partition()` 并不是 Python 内置的方法,因为 `set` 类型本身就不保留项目的顺序。因此,`set.partition()` 不是一个有效的方法。 不过,我们可以通过手动编写代码来模拟 `set.partition()` 的行为。例如,假设我们有一个字符串集合 `{'apple', 'banana', 'cherry', 'date'}`,我们想要将它们分为两部分:以字母 'a' 开头的字符串和不以字母 'a' 开头的字符串。我们可以使用以下代码: ```python strings = {'apple', 'banana', 'cherry', 'date'} a_start = set(filter(lambda s: s.startswith('a'), strings)) not_a_start = strings - a_start print(a_start) # {'apple'} print(not_a_start) # {'banana', 'cherry', 'date'} ``` 这段代码使用了 Python 内置的 `filter()` 函数和 `set` 类型的差集运算。它首先使用 `filter()` 函数找到以字母 'a' 开头的字符串,然后使用差集运算将它们从原始集合中移除,得到不以字母 'a' 开头的字符串集合。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值