【Description】
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
【Idea】
分析题干需求,大致手写列一下解,即知用穷举法,立即推>>DFS
由于return形式是 list[ list[int] ], 所以在回溯时需要有一个temp list来暂存当前的求解list
【Solution】
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
self.resList = []
self.DFS(candidates, target, 0, [])
return self.resList
def DFS(self, candis, target, start, value_list):
if target == 0: # 存在一组数,和值等于target
return self.resList.append(value_list)
length = len(candis)
for i in range(start, length):
if target >= candis[i]:
self.DFS(candis, target-candis[i], i , value_list + [candis[i]])
else:
return
网友评论