[ LeetCode ] 40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is: 
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
思路: 這題跟 第39題 combination sum 小有差別
combination sum    可以想成 找零錢 然後手裡的零錢是無限的 請問有幾種找法?
combination sum II可以想成 找零錢 然後手裡的零錢是限的 請問有幾種找法?

我們可以在原本的 combination sum 上面做些改變:
1. 對candidates sort, 這可以讓我們之後輕易的判斷 candidate[i] == candidate[i-1] 是否一樣. 一樣的話直接跳過 (line 15)
2. 判斷path 是否在 res 出現過 (line 12)

Time complexity: O(n!), n = element in the candidates
Space complexity: O(m), the result of how many path we found




class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs( idx, candidates, path, target ):
            to = sum(path)
            if   to > target:  return # backtracking
            elif to == target:
                if path not in res : res.append(path[:])
            else:
                for i in range(len(candidates)):
                    if i > idx and candidates[i] == candidates[i-1]: continue
                    path.append(candidates[i])
                    dfs( idx+1, candidates[i+1:], path, target )
                    path.pop()

        res, path = [], []
        candidates.sort()
        dfs( 0, candidates, path, target )
        return res

留言