Combination Sum-LeetCode

topic:

Insert picture description here
Original link: https://leetcode-cn.com/problems/combination-sum/

Ideas:

  1. When it comes to the subject of permutation and combination, it will more or less involve retrospective thinking
  2. 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
  3. 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.
  4. 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:

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates = sorted(candidates)

        def dfs(begin,temp,remain):
            for i in range(begin, len(candidates)):
                c = candidates[i]
                if c==remain:
                    result.append(temp+[c])
                if c<remain:
                    dfs(i,temp+[c],remain-c)
                # 自动置空temp
                if c>remain:
                    return

        dfs(0,[],target)
        return result

Guess you like

Origin blog.csdn.net/qq_35221523/article/details/112855985