leetcode 39. Total composition (Python)

Given a non-repeating array element candidates and a target number target, you can find all the candidates for the target numbers and combinations thereof.

Unlimited numbers of candidates may be selected is repeated.

Description:

All figures (including the target) are positive integers.
Solution Set can not contain duplicate combinations thereof. 
Example 1:

Input: candidates = [2,3,6,7], target = 7,
the set is solved:
[
[7],
[2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
the set is solved:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        self.res = []
        if len(candidates) <= 0:
            return res
        candidates.sort()
        self.dfs(candidates,[],target,0)  # 递归回溯
        return self.res
            
    def dfs(self,candidates,sublist,target,last):  # last表示当前sublist的最后一个元素
        if target == 0:
            self.res.append(sublist) 
        if target < candidates[0]: # Pruning operation, the target value is smaller than the smallest element has a
             return  
        for NUM in candidates in a: # digital reusable, each time the head traverse the
             IF NUM> target: # pruning operation, when the current value is larger than the target value, the subsequent without traversing
                 return  
            IF NUM <last: # pruning operation: if the current is less than the current value of the last element of a sublist, then continue to traverse, prevent duplication solutions, such as [ 2 , 2 , 3 ], [ 3 , 2 , 2 ]
                 Continue 
            self.dfs (candidates in a, subList + [NUM], target-NUM, NUM)

Reference: https://blog.csdn.net/weixin_40546602/article/details/88357837 

Recursive function dfs (candidates, sublist, target, last), wherein the sub-array for the current record sublist satisfying the condition, last is the last element of the current sub-array.

Pruning Operation 1: Target value is less than the smallest element of the array element, there is no need to continue to traverse

2 pruning operation: this element is greater than the target value, the subsequent elements must be greater than the target value (sorted array), the condition is not satisfied, no need to continue to traverse

3 pruning operation: if the current is less than the current value of the last element of a sublist, then continue to traverse, prevent duplication solutions, such as [2,2,3], [3,2,2]

Guess you like

Origin www.cnblogs.com/xiaotongtt/p/11324330.html