Backpack problems 416. Partition Equal Subset Sum

2023-11-24 05:45

本文主要是介绍Backpack problems 416. Partition Equal Subset Sum,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 01 backpack

There are n objects and a backpack that can carry at most w weights. The weight of the ith object is weight[i] and the value obtained is value[i] . Each object can be used only once, so solve for which objects to put in the backpack that have the greatest sum of values.

1. 1. dp[i][j]:  represents the maximum sum of values of any objects taken from [0-i] and put into the backpack of capacity j.

2. nothing put in: dp[i][j] = dp[i - 1][j] , cuz weight[i] > j

    object put in : dp[i][j] = dp[i - 1][j - weight[i]] + value[i]

3. recurrence formula :  dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])

4.initialization: if j == 0:    dp[i][0] = 0

                          if j < weight[0]:   dp[0][j] = 0  elif j >= weight[0]:  dp[0][j] = value[0]

5. Traverse the item first or the pack weight first? 

both is ok,  traverse the item first is better to understand!

// weight数组的大小 就是物品个数
for(int i = 1; i < weight.size(); i++) { // 遍历物品
    for(int j = 0; j <= bagweight; j++) { // 遍历背包容量
        if (j < weight[i]) dp[i][j] = dp[i - 1][j];
        else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);

    }
}

---------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------------

一维dp数组(滚动数组)

One-dimensional dp arrays (rolling arrays)

In fact, it can be found that if the layer dp[i - 1] is copied onto dp[i], the expression could well be: dp[i][j] = max(dp[i][j], dp[i][j - weight[i]] + value[i])

1. dp[j] denotes: a backpack with capacity j. The value of the items carried can be maximized to dp[j].

2.recurrence formula :

dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); #不同的i对应同一个j时候

3.initialization

dp[0] = 0

4.One-dimensional dp array traversal order

for(int i = 0; i < weight.size(); i++) { // 遍历物品
    for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量
        dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);

    }
}

 The reverse order traversal is to ensure that item i is only put in once! But if once it is traversed in positive order, then item 0 will be rejoined multiple times!

---------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------------

416. Partition Equal Subset Sum

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.

 1-dimensional dp arrays:

 recurrence formula :  dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])    weight == value in this problem

class Solution:def canPartition(self, nums: List[int]) -> bool:if sum(nums) % 2 != 0:return Falsetarget = sum(nums) // 2dp = [0] * (target + 1)for num in nums:for j in range(target, num-1, -1):dp[j] = max(dp[j], dp[j-num] + num)return dp[-1] == target

2-dimensional dp arrays:

class Solution:def canPartition(self, nums: List[int]) -> bool:total_sum = sum(nums)if total_sum % 2 != 0:return Falsetarget_sum = total_sum // 2dp = [[False] * (target_sum + 1) for _ in range(len(nums) + 1)]# 初始化第一行(空子集可以得到和为0)for i in range(len(nums) + 1):dp[i][0] = Truefor i in range(1, len(nums) + 1):for j in range(1, target_sum + 1):if j < nums[i - 1]:# 当前数字大于目标和时,无法使用该数字dp[i][j] = dp[i - 1][j]else:# 当前数字小于等于目标和时,可以选择使用或不使用该数字dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]return dp[len(nums)][target_sum]

这篇关于Backpack problems 416. Partition Equal Subset Sum的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/421338

相关文章

最大流=最小割=最小点权覆盖集=sum-最大点权独立集

二分图最小点覆盖和最大独立集都可以转化为最大匹配求解。 在这个基础上,把每个点赋予一个非负的权值,这两个问题就转化为:二分图最小点权覆盖和二分图最大点权独立集。   二分图最小点权覆盖     从x或者y集合中选取一些点,使这些点覆盖所有的边,并且选出来的点的权值尽可能小。 建模:     原二分图中的边(u,v)替换为容量为INF的有向边(u,v),设立源点s和汇点t

如何导入sun.misc.BASE64Encoder和sum.misc.BASE64Decoder

右击项目名--->Build Path--->Configure Build Path...--->java Build Path--->Access rules:1 rule defined,added to all librar...   --->Edit --->Add...

nyoj 695 Judging Filling Problems

一道强大的模拟题。。。 只要学会<string>类的运用即可。。。 注意: 1、细节的处理。 2、问题的分情况讨论。。 附上代码: 有好对缀余的地方,希望大神前来更新。 #include<stdio.h>#include<string.h>#include<string>#include<iostream>using namespace std;int num[1000

18. 4 Sum

题目: 解答: 与之前的三数之和的解法类似,也是先排序,然后不断剔除不可能的条件,最后两个参数,通过两头求和计算得出。 代码: class Solution {public:vector<vector<int>> fourSum(vector<int>& nums, int target) {vector<vector<int>> result;int len = nums.size

apt-get update更新源时,出现“Hash Sum mismatch”问题

转载自:apt-get update更新源时,出现“Hash Sum mismatch”问题 当使用apt-get update更新源时,出现下面“Hash Sum mismatch”的报错,具体如下: root@localhost:~# apt-get update ...... ...... W: Failed to fetch http://us.archive.ubuntu.com/ub

力扣416-分割等和子集(Java详细题解)

题目链接:416. 分割等和子集 - 力扣(LeetCode) 前情提要: 因为本人最近都来刷dp类的题目所以该题就默认用dp方法来做。 最近刚学完01背包,所以现在的题解都是以01背包问题为基础再来写的。 如果大家不懂01背包的话,建议可以去学一学,01背包问题可以说是背包问题的基础。 如果大家感兴趣,我后期可以出一篇专门讲解01背包问题。 dp五部曲。 1.确定dp数组和i

[LeetCode] 303. Range Sum Query - Immutable

题:https://leetcode.com/problems/range-sum-query-immutable/description/ 题目 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums

[LeetCode] 64. Minimum Path Sum

题:https://leetcode.com/problems/minimum-path-sum/description/ 题目 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers

[LeetCode] 404. Sum of Left Leaves

题:https://leetcode.com/problems/sum-of-left-leaves/description/ 题目 Find the sum of all left leaves in a given binary tree. Example: 3/ \9 20/ \15 7There are two left leaves in the binary t

[LeetCode] 763. Partition Labels

题:https://leetcode.com/submissions/detail/187840512/ 题目 A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at mo