1. 程式人生 > >LeetCode40:Combination Sum II(回溯)

LeetCode40:Combination Sum II(回溯)

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] ]

LeetCode:連結

40Combination Sum II這道題跟上題區別不大,只是限制了每個數字只能使用一次所以for的時候i的起始位置就不是每次都從第一個數字添加了,而是要後移的。並且這個為了結果的去重,必須先將C陣列排序,然後回溯的時候是從小到大的

class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        ans, res = [], []
        candidates.sort()
        self.backtracking(candidates, target, 0, ans, res)
        return res

    def backtracking(self, candidates, target, start, ans, res):
        # 去重
        if target == 0 and ans not in res:
            res.append(ans)
        else:
            for i in range(start, len(candidates)):
                # 小於candidates[i] 可以減少判斷時間
                if target < candidates[i]:
                    break
                # i+1是為了限制每個數字只能使用一次
                self.backtracking(candidates, target-candidates[i], i+1, ans+[candidates[i]], res)