<filename>python/Backtracking/40.combination-sum-ii.py
"""

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:as
[
  [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]
]
"""


class Solution:
    def combinations(self, candidates, target):
        """
        与39题的区别是不能重用元素，而元素可能有重复；
        不能重用好解决，回溯的index往下一个就行；
        元素可能有重复，就让结果的去重麻烦一些；
        """
        size = len(candidates)
        if size == 0:
            return []
        candidates.sort()
        path = []
        res = []
        self._find_path(candidates, path, res, target, 0, size)
        return res

    def _find_path(self,candidates,path,res,target,begin,size):
        if target ==0:
            res.append(path.copy())
        else:
            for i in range(begin,size):
                left_num = target - candidates[i]
                if left_num < 0:
                    break
                # 如果存在重复的元素，前一个元素已经遍历了后一个元素与之后元素组合的所有可能
                if i>begin and candidates[i] == candidates[i-1]:
                    continue
                path.append(candidates[i])
                self._find_path(candidates,path,res,left_num,i+1,size)
                path.pop()