Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
题目大意:
题目大意与39题差不多,可以参考https://blog.youkuaiyun.com/qq_29600137/article/details/88419528
不同之处在于我们只能使用序列中给出的参数,序列中存在重复的参数。
解题思路:
生成排序并去重之后的序列,并计算出序列中每个参数的个数(单独保存为一个序列)。
维护好生成个数的序列DFS求解,注:对于本身就大于target的产生,我们可以将其去掉,时间可以从80ms提升到60ms
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
new_can = []
new_can.append(candidates[0])
for i in range(1,len(candidates)):
if candidates[i] != candidates[i-1]:
new_can.append(candidates[i])
len_c = len(new_can)
num = [0] * len_c
len_max = len_c
cor_loc = 0
num[0] += 1
for i in range(1,len(candidates)):
if candidates[i] != candidates[i-1]:
cor_loc += 1
num[cor_loc] += 1
for i in range(len_c):
if int(target / new_can[i]) == 0 and i < len_max:
len_max = i
ans = []
tmp = []
began = 0
return DFS(ans, tmp, 0, target, len_max ,num, new_can, began)
def DFS(ans, tmp, cor, target, len_max, num, candidates, began):
if cor > target:
return ans
if cor == target:
new_ans = []
for i in range(len(tmp)):
new_ans.append(tmp[i])
ans.append(new_ans)
return ans
for i in range(began, len_max):
if num[i] != 0 and cor + candidates[i] <= target:
tmp.append(candidates[i])
num[i] -= 1
cor += candidates[i]
ans = DFS(ans, tmp, cor, target, len_max, num, candidates, i)
tmp.pop()
num[i] += 1
cor -= candidates[i]
return ans