“””
39. Combination Sum
Description
HintsSubmissionsDiscussSolution
Given a set of candidate numbers (C) (without duplicates) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
"""
import copy
class Solution:
def recursive(self,candidates,target_cur,nums_in,numlist_cur):
"""
分為 每次從set裡邊迴圈所有數,已有值減去所有數,新值作為已有值,繼續處理。遇到0 返回儲存,負數去掉
:param candidates:
:param target:
:return:
"""
# numlist_cur_in=numlist_cur
outlist=[]
for index,num in enumerate(candidates):
target_cur_new=target_cur-num
if target_cur_new==0:
numlist_cur.append(nums_in+[num])
elif target_cur_new>0:
self.recursive(candidates[index:],target_cur_new,nums_in+[num],numlist_cur)
else:
pass
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
numlist_cur=[]
out=self.recursive(candidates,target,[],numlist_cur)
return numlist_cur
# print(out)
# print(numlist_cur)
class Solution_:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
self.rec(candidates, target, [], res)
return res
def rec(self, candidates, target, path, res):
if target < 0:
return
if target == 0:
res.append(path)
return
for i in range(len(candidates)):
self.rec(candidates[i:], target - candidates[i], path + [candidates[i]], res)
if __name__==`__main__`:
st=Solution()
nums=[2, 3, 6, 7]
target=6
out=st.combinationSum(nums,target)
print(out)