【leetcode】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.

思路:用了一个最笨的方法,先算出来数组中所有数的总和sum,如果sum不能被2除断那么很明显无法分成两个和都相同的两组。如果能除断,那么就看数组中是否有和加起来等于sum/2 的组合了,用dp[i] 表示当前数组中加起来和等于i 的数的和。如果dp[sum/2] == sum/2,那么说明有组合加起来等于sum/2。


c++代码(312ms)

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%2)==1)
            return false;
        sum = sum/2;
        vector<int> dp(sum+1, 0);
        for(int i=0; i<len; i++){
            for(int j=sum; j>=1; j--){
                if(j>=nums[i]){
                    dp[j] = max(dp[j], nums[i]+dp[j-nums[i]]);
                }
            }
        }
        return dp[sum]==sum;
    }
};




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值