当前位置:网站首页>494. Target sum · depth first search · knapsack problem
494. Target sum · depth first search · knapsack problem
2022-07-25 00:14:00 【Xiao Xun wants to be strong】
link :https://leetcode.cn/problems/target-sum/solution/by-xun-ge-v-gmb5/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
subject
Example
Ideas
Their thinking
- Depth-first search
It is easy to think of when you see the topic dfs Violence enumerates every element , There are two situations for each element
- Is a positive number --> Add the previous enumeration
- It's a negative number --> Subtract the cases enumerated before
Finally, when enumerating to the last element, judge whether the condition is satisfied , Satisfy +1, dissatisfaction +0.
- Dynamic programming , Convert to 0 1 knapsack problem

The topic needs to split the non empty array nums Is two arrays , This array partition makes the sum of the elements of the two subsets equal .
You can change the topic to , take nums After summing the array , Divide by half , Then in the array nums Whether it is possible to find the accumulation and equality of any element in , The only element that does not repeat the selection
In fact, after changing the topic and Change for The topic idea is almost . It's all about backpacking
It's equivalent to giving us a backpack with limited capacity and a pile of things , We need to put these things in our backpacks , Now we just need to judge whether it can be exactly filled , I don't care what's in it , How much is it loaded .
So we apply for two-dimensional dp[i][j] Array , Record what we can pack on this back , Is it full , There are two states when you meet something
- Not loaded :
- dp[i][j] = dp[i-1][j], I didn't install it. I inherited the last backpack state
- installed :
- Just full dp[i][j] = true
- Yes, but not yet full :dp[i][j] = dp[i-1][j-nums[i]], I packed it , Judge if there is anything else I can fill with this stuff
For example, the size of the backpack is 5, There's something 1,2,3,4( It has nothing to do with the subject ),dp[i][j] It means that the backpack is big j when , Chose something i, The current backpack is full (true), Still not full (false), therefore dp[1][2] by true, It means I chose something 2 And the size of the backpack is 2 when , My backpack is full , therefore dp[2][3]=true, that dp[2][5] = dp[2][3] + dp[1][2] = true, My backpack is 5, You can choose to pack things 3 And things 2, When the size of the backpack can't hold my things, inherit i-1 Backpack status , Because I can choose not to install the current thing , Then the backpack will not change , And so on , Finally back to dp[][max_j] Full or not
Space compression
You can see that from the top , We don't care what's in the backpack , Then is it unnecessary to apply for recording the size of the contents , Of course you can , We only care about whether the backpack can be filled , So we apply dp[n] Record the backpack size as n Can it be filled when , But when loading things, you need to start with a big backpack , Because this can keep the last backpack state
The sum must be even , Odd number /2 There is .5 No matter how we find it, we can't find decimals in the integer array
Code
Depth-first search
/*
*int findTargetSumWays(int* nums, int numsSize, int target)
int findTargetSumWays: The number of times that different expression values in the array are equal to the target value
int* nums: Array
int numsSize: The length of the array
int target: The target
Return value : Number of valid expressions
*/
int dfs(int * nums, int inode, int numsSize, int sum, int target)
{
if(inode == numsSize){// Enumerate to the last element
if(sum == target){// Valid expressions , Meet the requirements of the topic
return 1;
}
else{// dissatisfaction
return 0;
}
}
return dfs(nums, inode+1, numsSize, sum+nums[inode], target) + dfs(nums, inode+1, numsSize, sum-nums[inode], target);// Add up all the cases
}
int findTargetSumWays(int* nums, int numsSize, int target){
return dfs(nums, 0, numsSize, 0, target);// Depth first search enumerates all elements
}
author :xun-ge-v
link :https://leetcode.cn/problems/target-sum/solution/by-xun-ge-v-gmb5/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .Dynamic programming , Convert to 0 1 knapsack problem
/*
*int findTargetSumWays(int* nums, int numsSize, int target)
int findTargetSumWays: The number of times that different expression values in the array are equal to the target value
int* nums: Array
int numsSize: The length of the array
int target: The target
Return value : Number of valid expressions
*/
int findTargetSumWays(int* nums, int numsSize, int target){
int sum = 0;
for(int i = 0; i < numsSize; i++)// Sum up
{
sum += nums[i];
}
int diff = sum-target;
if(diff < 0 || diff % 2 != 0)// A special case
{
return 0;
}
int n = diff/2;
int dp[n+1];
memset(dp, 0, sizeof(int) * (n + 1));
dp[0] = 1;
for(int i = 0; i < numsSize; i++)// Enumerate things
{
for(int j = n; j >= nums[i]; j--)// Update your backpack
{
dp[j] += dp[j - nums[i]];
}
}
return dp[n];
}
author :xun-ge-v
link :https://leetcode.cn/problems/target-sum/solution/by-xun-ge-v-gmb5/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .Time and space complexity

边栏推荐
- Pointers and arrays
- C语言学习之分支与循环语句
- [mindspore ascend] [user defined operator] graph_ In mode, customize how to traverse tensor
- SQL result export function. If you click the work order but don't enter it, the interface is always blank and there is no response. What should you do?
- Regular expression learning
- Server intranet and Extranet
- HTB-Aragog
- 痛并快乐的-NIO编程
- Kubernetes application design guide
- Redis memory analysis tool RMA usage
猜你喜欢

NXP i.mx6q development board software and hardware are all open source, and the schematic diagram of the core board is provided

来自大佬洗礼!2022 头条首发纯手打 MySQL 高级进阶笔记, 吃透 P7 有望

From the big guy baptism! 2022 headline first hand play MySQL advanced notes, and it is expected to penetrate P7

痛并快乐的-NIO编程

Managing databases in a hybrid cloud: eight key considerations

Processing PDF and JPG files in VB6

指针与数组

The model needs to use two losses_ FN, how to operate?

1、 MFC introduction

C语言学习之分支与循环语句
随机推荐
50 places are limited to open | with the news of oceanbase's annual press conference coming!
Weekly summary (*66): next five years
Simple operation K6
Are you still using system. Currenttimemillis()? Take a look at stopwatch
软考 --- 程序设计语言基础(下)
Netease game Flink SQL platform practice
Ggplot2 visual faceting, visual faceted ridge plot with facet_wrap, and customize the background color of the faceted icon title box
Unity+photon self made multiplayer TPS game
Answers to some problems encountered in the process of Xperia XZ (f8332) brushing and root
How to make five kinds of data structures in redis
数组中只出现一次的两个数字
Processing PDF and JPG files in VB6
Pit record: typeerror:'module'object is not callable
Lambda&Stream
Promtool Check
Internal network mapping port to external network
[mindspore] [training warning] warning when executing training code
Wechat applet development learning 5 (custom components)
Video chat source code - one-to-one live broadcast system source code
Oracle is not null cannot filter null values