当前位置:网站首页>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;
}边栏推荐
- 杂志特稿:元宇宙将重塑我们的生活,我们要确保它变得更好
- Local empowerment learning
- STM32 concept and installation [day 1]
- The third week of summer vacation
- jenkins多任務並發構建
- Jenkins multitâche construction simultanée
- [重要通知]星球线上培训第三期来袭!讲解如何在QTYX上构建自己的量化策略!...
- 以科技传递温度,vivo守护生物多样性之美
- Install go environment under Kali
- Exchange 2010 wildcard SSL certificate installation document
猜你喜欢

Precautions for using XXL job

浅谈领域驱动设计

ASP.NET CORE写一个缓存Attribute工具

Running around, market and quantitative page function optimization! Stock quantitative analysis tool qtyx-v2.4.5

Install SSL Certificate in Litespeed web server

医院无线网络系统设计

On the possibility and limitation of defi in the metauniverse

Solve the problem that the script tag is written in front of the element node and cannot get the element node
![[bdsec CTF 2022] partial WP](/img/00/25c1953a324fbf04e3baf592079978.png)
[bdsec CTF 2022] partial WP

Try to run this command from the system terminal Make sure that you use the correct
随机推荐
毕业设计校园信息发布平台网站源码
Running around, market and quantitative page function optimization! Stock quantitative analysis tool qtyx-v2.4.5
Summary of the first change to open source middleware keycloak
5年接觸近百比特老板,身為獵頭的我,發現昇職的秘密不過4個字
College degree want to 0 basic programming after looking for a job feasible?
机房建设资料
STM32 installation tutorial and j-link burning driver installation tutorial [the next day]
Async await details & Promise
About rapidssl certificate
利用canvas画图片
Perlin noise and random terrain
Exchange 2010 wildcard SSL certificate installation document
[important notice] the third phase of planet online training is coming! Explain how to build your own quantitative strategy on qtyx
Database design
Improvement of DB file sequential read caused by insert
What is naked SQL? What middleware or plug-in is good for express to operate MySQL?
快速排序注意点
深入了解-微信开发者工具
Detailed comparison between graphic array and linked list, performance test
[bdsec CTF 2022] partial WP