Combination Sum I, II
LeetCode 39, 40
I
class Solution:
def combinationSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if not nums:
return []
self.res = []
self.dfs(nums, target, [], 0)
return self.res
def dfs(self, nums, target, path, index):
if target ==0:
self.res.append(path)
if target < 0:
return
# 當圖往下畫時, 你就會有感覺需要用 for loop
for i in range (index, len(nums)):
self.dfs(nums, target - nums[i], path+[nums[i]], i)
# 這會迴傳 [[2,2,3],[7]]
#
# self.dfs(nums, target - nums[i], path+[nums[i]], index)
# 底下會迴傳[[2,2,3],[2,3,2],[3,2,2],[7]] II
The solution set must not contain duplicate combinations
Last updated