当前位置:网站首页>leetcode494,474
leetcode494,474
2022-07-05 00:23:00 【The left wheel of fate】
List of articles
494. Objectives and
Give you an array of integers nums And an integer target .
Add... Before each integer in the array '+' or '-' , And then concatenate all the integers , You can construct a expression :
for example ,nums = [2, 1] , Can be in 2 Before adding '+' , stay 1 Before adding '-' , And then concatenate them to get the expression "+2-1" .
Returns the 、 The result is equal to target Different expression Number of .
Example 1:
Input :nums = [1,1,1,1,1], target = 3
Output :5
explain : Altogether 5 Ways to make the ultimate goal and 3 .
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input :nums = [1], target = 1
Output :1
Tips :
1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
analysis
- Change your mind , Divide into sets that only do addition and sets that do subtraction ,add and sub For the sum of each set . And that gives us
add+sub = Sum,add-sub = target
Sum and target All fixed , By elimination , We can get2*add = Sum+target
therefore ,add =(Sum+target)/2
, Here we need to consider whether it is possible Sum+target In the case of an odd number . If it's odd ,Sum and target It must be odd and even . - Sum If it's odd ,add and sub It must be odd and even , but add-sum It is concluded that the target Must be strange , Contradiction with odd and even .
- Sum If it's even ,add and sub It may be two odd or two even , but add-sum It is concluded that the target It must happen , Contradiction with odd and even .
- So if Sum+target For an odd number , The answer does not exist .
- Yes nums Array mapping , Make each number absolute , If the sum is less than target, It cannot exist , That is, each state with the largest number cannot add up to the largest , Then the answer does not exist . If the opposite of the sum is greater than target, It cannot exist , That is, the superposition of states with the smallest number cannot be minimized , Then the answer does not exist .
- dp open up add+1 Space ,
dp[j] Indicates that the backpack capacity is j when , The number of different expressions is dp[j]
- Is still 01 knapsack , Familiar first traverse items , Then traverse the backpack in reverse , For recurrence
dp[j]+=dp[j-nums[i]]
, This is a recursive formula commonly used in finding combinations , Be carefuldp[0] = 1
, The initial state should be set .
Code ( Dynamic programming )
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
# Split into two parts
Sum = sum(nums)
if (Sum+target) % 2 == 1:
return 0
abs_nums = list(map(abs,nums))
if sum(abs_nums) < target or -sum(abs_nums) > target:
return 0
if len(nums) == 1 and abs(nums[0]) != abs(target):
return 0
add = (Sum+target)//2
dp = [0] * (add+1) # dp[j] The capacity is j The backpack , Yes dp[j] A way to fill
dp[0] = 1
for i in range(len(nums)): # Traverse the items
for j in range(add,nums[i]-1,-1): # Traverse the knapsack in reverse
dp[j] += dp[j - nums[i]] # fill j The method of is equal to filling j Method plus reserved space
return dp[add]
Through screenshots
474. One and zero
Here's an array of binary strings strs And two integers m and n .
Please find out and return to strs Length of the largest subset of , This subset most Yes m individual 0 and n individual 1 .
If x All of the elements of are also y The elements of , aggregate x Is a collection y Of A subset of .
Example 1:
Input :strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
Output :4
explain : At most 5 individual 0 and 3 individual 1 The largest subset of is {"10","0001","1","0"} , So the answer is 4 .
Other smaller subsets that satisfy the question include {"0001","1"} and {"10","1","0"} .{"111001"} Not satisfied with the question , Because it contains 4 individual 1 , Greater than n Value 3 .
Example 2:
Input :strs = ["10", "0", "1"], m = 1, n = 1
Output :2
explain : The largest subset is {"0", "1"} , So the answer is 2 .
Tips :
1 <= strs.length <= 600
1 <= strs[i].length <= 100
strs[i] Only by '0' and '1' form
1 <= m, n <= 100
analysis
- two-dimensional 01 knapsack ( Think of this backpack as a flat piece of cloth )
- The two dimensions are :0 and 1 The number of
- Because it is two-dimensional 01 knapsack , We need to open up a two-dimensional array .dp[i][j] Indicates that there is a length of i, Width is j The largest subset of this cloth can have . One dimensional backpack , Generally, weight is the constraint condition or the size of number , Two dimensions have double constraints . thus , I think the three-dimensional container problem can be solved by dynamic programming , Is in a three-dimensional space , Put boxes of different sizes , How to put the highest efficiency .
- Go through the items first , Work out 0 and 1 The number of , The other two dimensions are reverse traversal , Equivalent to the capacity of the backpack .
- Because it is to find the largest subset , There must be
dp[j][z] = max(dp[j][z],dp[j-zero][z-ones]+1)
,+1 Is to add this traversed subset , It's very similar to when we calculate the value , discharge i The value of time isdp[i][j-1] + value[i]
, Empathy , Let go of j,z The number of subsets after two dimensions isdp[j-zero][z-ones]+1)
Code ( Dynamic programming )
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
# 01 knapsack
# dp[i][j] Express i individual 0 Capacity and j individual 1 The largest subset of capacity backpacks can hold
# i,j It means weight , Jointly control the double boundaries
# The number of subsets is the maximum value
dp = [[0]*(n+1) for _ in range(m+1)]
for i in strs: # Traverse the items
zero = i.count('0')
ones = i.count('1')
for j in range(m,zero-1,-1):
for z in range(n,ones-1,-1):
dp[j][z] = max(dp[j][z],dp[j-zero][z-ones]+1)
return dp[m][n]
Through screenshots
If there is a mistake , Please correct me , Welcome to exchange , thank you *(・ω・)ノ
边栏推荐
- Life is changeable, and the large intestine covers the small intestine. This time, I can really go home to see my daughter-in-law...
- How to avoid arc generation—— Aafd fault arc detector solves the problem for you
- Using fast parsing intranet penetration to realize zero cost self built website
- 雅思考试流程、需要具体注意些什么、怎么复习?
- AcWing164. 可达性统计(拓扑排序+bitset)
- 兩個數相互替換
- Netcore3.1 JSON web token Middleware
- 图解网络:什么是网关负载均衡协议GLBP?
- P4408 [NOI2003] 逃学的小孩(树的直径)
- [IELTS reading] Wang Xiwei reads P4 (matching2 paragraph information matching question [difficult])
猜你喜欢
2022.07.03(LC_6108_解密消息)
abc 258 G - Triangle(bitset)
abc 258 G - Triangle(bitset)
Netcore3.1 JSON web token Middleware
【selenium自动化】常用注解
[paper reading] Tun det: a novel network for meridian ultra sound nodule detection
Every time I look at the interface documents of my colleagues, I get confused and have a lot of problems...
Skills in analyzing the trend chart of London Silver
同事的接口文档我每次看着就头大,毛病多多。。。
Learning of basic amplification circuit
随机推荐
[paper reading] Tun det: a novel network for meridian ultra sound nodule detection
多回路仪表在基站“转改直”方面的应用
如何有效对直流列头柜进行监测
OpenHarmony资源管理详解
uniapp微信小程序拿来即用的瀑布流布局demo2(方法二)(复制粘贴即可使用,无需做其他处理)
[error reporting] "typeerror: cannot read properties of undefined (reading 'split')“
go踩坑——no required module provides package : go.mod file not found in current directory or any parent
Réseau graphique: Qu'est - ce que le Protocole d'équilibrage de charge de passerelle glbp?
22-07-02周总结
How many triangles are there in the golden K-line diagram?
URL和URI
P4408 [noi2003] truant children (tree diameter)
How to save your code works quickly to better protect your labor achievements
Some basic functions of enterprise projects are developed, and important things are saved to online first a
Get to know ROS for the first time
js如何实现数组转树
Detailed explanation of openharmony resource management
Acrel-EMS综合能效平台在校园建设的意义
Remember to build wheels repeatedly at one time (the setting instructions of obsidian plug-in are translated into Chinese)
GDB common commands