1. 程式人生 > >Leetcode篇:組合總和II

Leetcode篇:組合總和II


@author: ZZQ
@software: PyCharm
@file: combinationSum2.py
@time: 2018/11/15 18:38
要求:給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
所有數字(包括目標數)都是正整數。
解集不能包含重複的組合。
示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集為:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
輸入: candidates = [2,5,2,1,2], target = 5,
所求解集為:
[
[1,2,2],
[5]
]
思路; 深搜+ 減枝
注意停止: 如果當前temp_ans > target, 則停止, return
注意每個元素只能使用一次, 先對陣列進行排序,然後每次深搜都從下一個元素開始。
注意拷貝temp_ans到新的陣列中,再存入ans中。

import copy
class Solution():
    def __init__(self):
        pass

    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        can_len = len(candidates)
        if can_len == 0:
            return []
        ans = []
        temp_ans = []
        temp_sum = 0
        start_index = -1
        self.dfs(temp_ans, temp_sum, start_index, target, candidates, ans)
        return ans

    def dfs(self, temp_ans, temp_sum, start_index, target, candidates, ans):
        if temp_sum == target:
            tt_ans = copy.deepcopy(temp_ans)
            ans.append(tt_ans)
            return
        if temp_sum > target:
            return
        for i in range(start_index+1, len(candidates)):
            if i > start_index+1 and candidates[i] == candidates[i-1]:
                continue
            temp_ans.append(candidates[i])
            self.dfs(temp_ans, temp_sum + candidates[i], i, target, candidates, ans)
            temp_ans.pop()