LeetCode Medium: 40. Combination Sum II
一、题目
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] ]
题意:与上一道题相似,不同的是这道题数组中的数字只能使用一次。
二、思路
每一个数字在使用后都做一次标记 flaglist,使用后置 1 ,在一次递归过程中遇到 flaglist 为 1的时候就跳过;还有就是如果给定的数组就是带有重复的,那么在排序后相同的数字肯定是近邻着的,这时候在递归的时候需要做一些处理。
三、代码
#utf-8
class Solution:
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.reList = []
f1 = [0]*len(candidates)
candidates = sorted(candidates)
self.dfs(candidates, [], target, f1,0)
print(self.reList)
return self.reList
def dfs(self,candidates,sublist,target,flaglist,last):
if target == 0:
self.reList.append(sublist[:])
if target < candidates[0]:
return
l = None #为了防止重复的比如两个1,那么一层递归只处理一次
for m in range(len(candidates)):
n = candidates[m]
if n > target:
return
if n < last or flaglist[m] == 1 or l == n:
#三种情况:1、因为是从小到大,所以n开始要从上一个数以后;2、如果已经使用过,那就继续;3、如果在这一层递归的时候比如有两个1,那之前做一次1的时候,第二次就不处理了,不然就会重复
continue
sublist.append(n)
flaglist[m]=1
self.dfs(candidates,sublist,target-n,flaglist,n)
flaglist[m]=0
l = n
sublist.pop()
if __name__ == '__main__':
candidates = [2,4,3,1,1]
target = 5
ss = Solution()
ss.combinationSum2(candidates,target)
参考博客:https://blog.csdn.net/zl87758539/article/details/51693549
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号