Original link: https://leetcode-cn.com/problems/combination-sum/
Ideas:
When it comes to the subject of permutation and combination, it will more or less involve retrospective thinking
The key to this question is " Elements can be selected without restriction ", so unlike the full arrangement, the used array cannot be used to reduce the branch size
The rest of the ideas are in line with the typical backtracking algorithm, that is, each time the next application number is selected, if it does not meet, it will take a step back and select another number except the number.
After sorting, unnecessary judgments can be reduced, such as 235 and 5. If 2+3 is already greater than the given number 5, then there is no need to judge the 2+5 step back, because it must be greater than 5, and you can directly restart from 3. Start backtracking
Code:
classSolution:defcombinationSum(self, candidates: List[int], target:int)-> List[List[int]]:
result =[]
candidates =sorted(candidates)defdfs(begin,temp,remain):for i inrange(begin,len(candidates)):
c = candidates[i]if c==remain:
result.append(temp+[c])if c<remain:
dfs(i,temp+[c],remain-c)# 自动置空tempif c>remain:return
dfs(0,[],target)return result