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.

 

Approach #1: DP. [C++]

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = std::accumulate(nums.begin(), nums.end(), 0);
        if (sum % 2 != 0) return false;
        vector<int> dp(sum+1, 0);
        dp[0] = 1;
        for (int num : nums) {
            for (int i = sum; i >= 0; --i) 
                if (dp[i]) dp[i+num] = 1;
            if (dp[sum/2]) return true;
        }
        return false;
    }
};

  

Analysis:

dp[i][j] : whether we can sum to j using first i numbers.

dp[i][j] = true if dp[i-1][j-num]

check dp[n-1][sum/2]

init dp[-1][0] = true

 

Time complexity: O(n^2*sum) -> O(n*sum)

Space complexity: O(sum)

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10404051.html

背包问题是动态规划中一个经典问题,它可以用来训练编程者对动态规划的理解和应用能力。在LeetCode中,01背包问题是一个典型的动态规划题目,题号通常为416. Partition Equal Subset Sum或者494. Target Sum,需要利用动态规划来判断是否存在子集的和等于一个给定的目标值。 参考资源链接:[LeetCode刷题攻略:C++解题技巧与101道精华题解析](https://wenku.csdn.net/doc/64qug1p6pv?spm=1055.2569.3001.10343) 在C++中解决背包问题通常涉及到使用一个二维数组dp[i][j],表示从数组的前i个物品中选取,能否填满容量为j的背包。初始化dp数组时,dp[0][...]应该设为false,因为没有物品时无法填满任何容量的背包;而dp[...][0]则设为true,因为容量为0的背包不选任何物品即可被填满。 以01背包为例,算法步骤如下: 1. 定义dp数组,dp[n+1][target+1],其中n为物品数量,target为背包最大承重。 2. 初始化dp数组:dp[0][...]为false,dp[...][0]为true。 3. 遍历物品i,从1到n。 4. 遍历容量j,从1到target。 5. 如果当前物品i的重量大于容量j,dp[i][j] = dp[i-1][j](不取当前物品)。 6. 否则,dp[i][j] = dp[i-1][j] || dp[i-1][j-weights[i-1]](取或不取当前物品)。 7. 最终dp[n][target]的值即为是否可以填满背包的答案。 C++代码示例: ```cpp bool canPartition(vector<int>& nums) { int sum = 0; for (int num : nums) sum += num; if (sum % 2 != 0) return false; int target = sum / 2; vector<vector<bool>> dp(nums.size() + 1, vector<bool>(target + 1, false)); for (int i = 0; i <= nums.size(); ++i) dp[i][0] = true; for (int i = 1; i <= nums.size(); ++i) { for (int j = 1; j <= target; ++j) { if (j < nums[i - 1]) { dp[i][j] = dp[i - 1][j]; } else { dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; } } } return dp[nums.size()][target]; } ``` 通过上述步骤和代码示例,可以深入理解动态规划解决背包问题的基本思想。对于想要更深入学习动态规划的读者,推荐阅读《LeetCode刷题攻略:C++解题技巧与101道精华题解析》一书,其中提供了关于背包问题及其它多种算法题目的详细解析和实用技巧,对于掌握C++在算法题目中的应用非常有帮助。 参考资源链接:[LeetCode刷题攻略:C++解题技巧与101道精华题解析](https://wenku.csdn.net/doc/64qug1p6pv?spm=1055.2569.3001.10343)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值