当前位置:网站首页>The combination sum of C language power deduction question 39. Backtracking method and traversal method
The combination sum of C language power deduction question 39. Backtracking method and traversal method
2022-07-24 02:10:00 【Take care of two dogs and never let them go bad】
To give you one No repeating elements Array of integers for candidates And a target integer target , find candidates You can make the sum of numbers as the target number target Of all Different combinations , And return... As a list . You can press In any order Return these combinations .
candidates Medium The same Numbers can Unlimited repeat selected . If the selected number of at least one number is different , Then the two combinations are different .
For a given input , Guarantee and for target The number of different combinations of is less than 150 individual .
Example 1:
Input :candidates = [2,3,6,7], target = 7
Output :[[2,2,3],[7]]
explain :
2 and 3 Can form a set of candidates ,2 + 2 + 3 = 7 . Be careful 2 You can use it multiple times .
7 Is also a candidate , 7 = 7 .
Only these two combinations .
Example 2:
Input : candidates = [2,3,5], target = 8
Output : [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input : candidates = [2], target = 1
Output : []
Tips :
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate Every element in is Different from each other
1 <= target <= 500
source : Power button (LeetCode)
link :https://leetcode.cn/problems/combination-sum
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Thought analysis :
Method 1 : backtracking
According to the example 1: Input : candidates = [2, 3, 6, 7],target = 7.
There are... In the candidate array 2, If a combination is found, the sum is 7 - 2 = 5 All combinations of , Add... Before 2 , Namely 7 All combinations of ;
In the same way 3, If a combination is found, the sum is 7 - 3 = 4 All combinations of , Add... Before 3 , Namely 7 All combinations of , Find it in this order .
Based on the above ideas , You can draw the following tree diagram . I suggest you draw this tree on paper , This kind of problem needs to draw a tree diagram first , And then coding implementation .
Code through Depth-first traversal Realization , Use a list , stay Depth-first traversal In the process of change , Traverse all possible lists and judge whether the current list meets the requirements of the topic , Become a backtracking algorithm .

- With target = 7 by Root node , Subtract when creating a branch ;
- Each arrow indicates : Subtract the value on the edge from the value of the parent node , Get the value of the child node . The value of the edge is given in the title candidate The value of each element of the array ;
- Reduced to 000 Or stop when it's negative , namely : node 000 And negative nodes become leaf nodes ;
- All from root node to node 000 The path of ( Only from top to bottom , There's no loop ) This is the result of the topic .
But only considering this will produce repetition .
The optimization is as follows : From the... Of each floor 222 Start with a node , Can no longer search to generate nodes of the same layer that have been used candidate Elements in .

Method 2 : Ergodic method
The most important thing of traversal is to determine the number of traversals
In fact, it can be thought that if the maximum length of the combination that conforms to the meaning of the question can be determined a, So you can use it a Time for Cycle through , And this a Is available , Just use target Divide by the smallest value in the array to get theoretically , The maximum length of the combination . Then there is another problem, that is, how to write a a Time of for loop , Recursion can do it , stay for Recursion is used in the loop . The final performance is slower than the backtracking algorithm
int *path;
int pathTop;
int **result;
int resultTop;
int *length;
void backTrack(int *candidates,int candidatesSize,int target, int sum , int index){
if(sum>target)
return ;
if(sum == target){
int *temp = malloc(sizeof(int)*pathTop);
for(int i=0;i<pathTop;i++){
temp[i] = path[i];
}
result[resultTop] = temp;
length[resultTop++] = pathTop;
return ;
}
for(int j=index; j<candidatesSize && sum<=target;j++){
sum = sum + candidates[j];
path[pathTop++] = candidates[j];
backTrack(candidates,candidatesSize,target,sum,j);
sum = sum - candidates[j];
pathTop--;
}
}
int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes){
pathTop = resultTop = 0;
path = malloc(sizeof(int)*100);
result = malloc(sizeof(int*) *500);
length = malloc(sizeof(int) *500);
backTrack(candidates,candidatesSize,target,0,0);
*returnSize = resultTop;
*returnColumnSizes = malloc(sizeof(int) *500);
for(int i =0 ; i<resultTop ; i++){
(*returnColumnSizes)[i] = length[i];
}
return result;
}边栏推荐
- Hospital network security architecture
- 小散量化炒股记|基于多任务爬虫技术, 实现A股实时行情Level1采样
- Hospital generic cabling
- Deliver temperature with science and technology, vivo protects the beauty of biodiversity
- Express operates mysql. What is wrong with the SQL?
- Structure the second operation of the actual combat battalion module
- 什么叫裸写SQL?express操作mysql用什么中件间或插件好呢?
- Basic knowledge of mathematical vector
- Where is the safest place to open a futures account now with the lowest handling fee?
- In depth understanding - wechat developer tools
猜你喜欢

Jmeter+influxdb+grafana pressure measurement real-time monitoring platform construction

奔走相告,行情与量化页面功能优化!股票量化分析工具QTYX-V2.4.5

ggplot2显示png

Visual full link log tracking

How to install, download and use the latest version of IDM software

图解数组和链表详细对比,性能测试

Deliver temperature with science and technology, vivo protects the beauty of biodiversity

分布式资源管理与任务调度框架Yarn

Hospital generic cabling
![[C language operation of linked list (initialization, establishment, length calculation, addition, deletion, and output of linked list)]](/img/9b/e5cda39c04d0cc2f69e43c97ee997d.png)
[C language operation of linked list (initialization, establishment, length calculation, addition, deletion, and output of linked list)]
随机推荐
毕业设计校园信息发布平台网站源码
Is it safe for Huatai Securities to open an account? Is it true? Is it formal
2022-07-22: what is the output of the following go language code? A:1; B:1.5; C: Compilation error; D:1.49。 package main import “fmt“ func main() { var i
The implementation method pathlisttomap can convert the input pathlist into a map type with hierarchical structure
Deliver temperature with science and technology, vivo protects the beauty of biodiversity
After five years of contact with nearly 100 bosses, as a headhunter, I found that the secret of promotion was only four words
Small volume stock trading record | based on multi task crawler technology, realize level1 sampling of A-share real-time market
Loadrunner12 installation, recording the first script and the proxy server did not respond to the solution
快速排序注意点
Visual full link log tracking
[machine learning basics] common operations of Feature Engineering
CANopen communication - PDO and SDO
The communication principle between native components, applets and clients, and the operation principle of video, map, canvas, picker, etc
On the possibility and limitation of defi in the metauniverse
ASP. Net core write a cache attribute tool
[important notice] the third phase of planet online training is coming! Explain how to build your own quantitative strategy on qtyx
ASP.NET CORE写一个缓存Attribute工具
Bank of Nanjing approved the financial technology post in advance
jenkins多任务并发构建
About rapidssl certificate