LeetCode Medium: 40. Combination Sum II

1. The topic

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

 

Question meaning: Similar to the previous question, the difference is that the numbers in the array of this question can only be used once.
2. Ideas
 After each number is used, mark the flaglist once, use the post-set 1, and skip when the flaglist is 1 in a recursive process; and if the given array is repeated, then sort After the same number is definitely adjacent, at this time need to do some processing when recursive.
3. Code
#utf-8
class Solution:
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.reList = []
        f1 = [0]*len(candidates)
        candidates = sorted(candidates)
        self.dfs(candidates, [], target, f1,0)
        print(self.reList)
        return self.reList

    def dfs(self,candidates,sublist,target,flaglist,last):
        if target == 0:
            self.reList.append(sublist[:])
        if target < candidates[0]:
            return
        l = None #In order to prevent duplicates such as two 1s, then a layer of recursion is processed only once
        for m in range(len(candidates)):
            n = candidates[m]
            if n > target:
                return
            if n < last or flaglist[m] == 1 or l == n:
                #Three situations: 1. Because it is from small to large, n starts from the previous number; 2. If it has been used, then continue; 3. If there are two 1s in this level of recursion, for example, When doing 1 once before, it will not be processed the second time, otherwise it will be repeated
                continue
            sublist.append(n)
            flaglist[m]=1
            self.dfs(candidates,sublist,target-n,flaglist,n)
            flaglist[m]=0
            l = n
            sublist.pop()

if __name__ == '__main__':
    candidates = [2,4,3,1,1]
    target = 5
    ss = Solution()
    ss.combinationSum2(candidates,target)

  

 
 
 
 
 
Reference blog: https://blog.csdn.net/zl87758539/article/details/51693549
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253167&siteId=291194637