LeetCode 40. 組合總和 II(回溯)

題目描述

給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
所有數字(包括目標數)都是正
解集不能包含重複的組合。

在這裏插入圖片描述

思路

詳見鏈接

代碼

class Solution:
	def combinationSum2(self,candidates:List[int],target:int)->List[List[int]]:
		if not candidates:
			return []
		candidates.sort()
		n = len(candidates)
		res = []
		def backtrack(i,tmp_sum,tmp_list):
			if tmp_sum == target:
				res.append(tmp_list)
				return
			for j in range(i,n):
				if tmp_sum + candidates[j] > target:
					break
				if j > i and candidates[j] == candidates[j-1]:
					continue
				backtrack(j+1,tmp_sum+candidates[j],tmp_list+[candidates[j]])
		backtrack(0,0,[])
		return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章