비 반복 배열 요소 후보와 대상 번호 대상을 감안할 때, 당신은 그 목표 숫자와 조합에 대한 모든 후보를 찾을 수 있습니다.
선택할 수있다 후보자의 무제한 숫자는 반복된다.
설명 :
(대상 포함) 모든 수치는 양의 정수이다.
솔루션 세트는 그 중복 조합을 포함 할 수 없습니다.
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.res = []
def helper(nums,tmp,i):
if tmp == target:
self.res.append(nums)
return
if tmp>target:
return
for j in range(i,len(candidates)):
helper(nums+[candidates[j]],tmp+candidates[j],j)
helper([],0,0)
return self.res
후보와 번호를 하나의 목표 대상의 배열을 감안할 때, 당신은 목표 숫자와 조합에 대한 모든 후보를 찾을 수 있습니다.
각 숫자 후보는 각 조합에서 한 번만 사용.
설명 :
(대상 번호를 포함하여) 모든 수치는 양의 정수이다.
솔루션 세트는 그 중복 조합을 포함 할 수 없습니다.역행
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