LeetCode 39. 組合總和(回溯+剪枝)

題目描述

給定一個無重複元素的數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。
candidates 中的數字可以無限制重複被選取。
說明:
所有數字(包括 target)都是正整數。
解集不能包含重複的組合。

在這裏插入圖片描述

思路

詳見鏈接

代碼

from typing import List
class Solution:
	def combinationSum(self,candidates:List[int],target:int)->List[List[int]]:
		size = len(candidates)
		if size == 0:
			return []
		candidates.sort()
		path = []
		res = []
		self._dfs(candidates,0,size,path,res,target)
		return res
	def _dfs(self,candidates,begin,size,path,res,target):
		if target == 0:
			res.append(path[:])
			return 
		for index in range(begin,size):
			residue = target - candidates[index]
			if residue < 0:
				break
			path.append(candidates[index])
			self._dfs(candidates,index,size,path,res,residue)
			path.pop()	
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章