当前位置:网站首页>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 *(・ω・)ノ
边栏推荐
- 【报错】 “TypeError: Cannot read properties of undefined (reading ‘split‘)“
- (script) one click deployment of any version of redis - the way to build a dream
- 【雅思阅读】王希伟阅读P4(matching2段落信息配对题【困难】)
- Is it safe to open an account in the College of Finance and economics? How to open an account?
- Fast parsing intranet penetration helps enterprises quickly achieve collaborative office
- 2022.07.03(LC_6111_统计放置房子的方式数)
- Learning of basic amplification circuit
- What is the difference between port mapping and port forwarding
- Specification for fs4061a boost 8.4v charging IC chip and fs4061b boost 12.6V charging IC chip datasheet
- 华为200万年薪聘请数据治理专家!背后的千亿市场值得关注
猜你喜欢
lambda表达式
【C】(笔试题)指针与数组,指针
Consolidated expression C case simple variable operation
快解析内网穿透帮助企业快速实现协同办公
PMP certificate renewal process
Summer challenge brings you to play harmoniyos multi terminal piano performance
In June, the list of winners of "Moli original author program" was announced! Invite you to talk about the domestic database
abc 258 G - Triangle(bitset)
2022.07.03(LC_6111_统计放置房子的方式数)
Microservice
随机推荐
P4408 [NOI2003] 逃学的小孩(树的直径)
[IELTS reading] Wang Xiwei reading P3 (heading)
[error reporting] "typeerror: cannot read properties of undefined (reading 'split')“
端口映射和端口转发区别是什么
Acwing164. Accessibility Statistics (topological sorting +bitset)
【C】(笔试题)指针与数组,指针
P3304 [sdoi2013] diameter (diameter of tree)
Design of emergency lighting evacuation indication system for urban rail transit station
Expand your kubecl function
《论文笔记》Multi-UAV Collaborative Monocular SLAM
Life is changeable, and the large intestine covers the small intestine. This time, I can really go home to see my daughter-in-law...
Build your own minecraft server with fast parsing
Paper notes multi UAV collaborative monolithic slam
URL和URI
巩固表达式C# 案例简单变量运算
2022.07.03(LC_6108_解密消息)
[Peking University] tensorflow2.0-1-opening
GDB常用命令
ORB(Oriented FAST and Rotated BRIEF)
如果炒股开华泰证券的户,在网上开户安全吗?