当前位置:网站首页>Leetcode knapsack problem
Leetcode knapsack problem
2022-06-22 13:21:00 【Linchong Fengxue mountain temple】

01 backpack theory
A two-dimensional dp

A one-dimensional dp

reflection
1. Why one dimension dp To flashback traversal
Because two-dimensional dp The upper and lower floors are separated from each other , It doesn't affect each other . A one-dimensional dp Influence between front and back , Only flashback traversal .
Completely backpack

Objectives and
01 knapsack




class Solution(object):
def findTargetSumWays(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
sumValue = sum(nums)
if target > sumValue or (sumValue + target) % 2 == 1 or (abs(target) > sumValue):
return 0
bagSize = (sumValue + target) // 2
dp = [0] * (bagSize + 1)
dp[0] = 1
for i in range(len(nums)):
for j in range(bagSize, nums[i] - 1, -1):
dp[j] += dp[j - nums[i]]
return dp[bagSize]474. One and zero
01 knapsack

class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0] * (n + 1) for _ in range(m + 1)] # Default initialization 0
# Traverse the items
for str in strs:
ones = str.count('1')
zeros = str.count('0')
# Traverse the backpack capacity and traverse from back to front !
for i in range(m, zeros - 1, -1):
for j in range(n, ones - 1, -1):
dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
return dp[m][n]518 Change for 2
Completely backpack

边栏推荐
猜你喜欢

leetcode-区间dp

RCE&代码执行漏洞

leetcode 1579. Ensure that the graph can be completely traversed

leetcode 968. Monitoring binary tree

769. Max Chunks To Make Sorted

SAP fi financial statement version setting

CVPR 2022 | visual language model pre training for scene text detection

leetcode LCP 10. 二叉树任务调度

Maui uses Masa blazor component library

基于SSM的图书馆管理系统,高质量毕业论文范例(可直接使用),项目导入视频,附送源码和数据库脚本,论文撰写教程
随机推荐
310. Minimum Height Trees
MySQL notes
934. Shortest Bridge
RobotFramework二次开发——实时日志
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
47. Permutations II
PostGIS through St_ Dwithin retrieves elements within a certain distance
AcWing第52场周赛
天坑专业学IC设计自学的话有公司会要吗
RCE&代码执行漏洞
Shell基础入门
阿里云磁盘性能分析
241. Different Ways to Add Parentheses
File download vulnerability & file read vulnerability & file delete vulnerability
130. Surrounded Regions
Rce & Code Execution Vulnerability
MySQL中触发器
OO2022第四单元作业总结
Alicloud disk performance analysis
JAXB元素详解
https://leetcode-cn.com/problems/coin-change/solution/dai-ma-sui-xiang-lu-dai-ni-xue-tou-wan-q-80r7/
https://programmercarl.com/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85.html#%E5%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85