题目描述:
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]
]
题目大意:
- 之所以称之为II,是因为有I,见LeetCode算法题之39. Combination Sum(medium)
- 与I大意类似,给定一个数组,一个目标值,找出数组中加和等于目标数的数的组合,区别在于,I,每个数用的次数不限,只要找出来,找全,即可
- 而II,每个数只能用一次
解题思路:
- 因为有了之前的想法,所以这次完全可以思路照搬
- 区别就在于用程序实现每次寻找的数,是没有用过的数字,其余判定条件是一样的
- 具体操作就是让程序用循环每次去找那个数后面的数,看有没有符合条件的
- 此句话给自己,若想真明白,需花时间,下功夫,把每一个变量到底是怎样变化弄清楚
少废话,上代码:
class Solution:
def combinationSum2(self, candidates, target):
candidates = sorted(candidates)#因为给定的是乱序的数组,升序排序
ans = []
def find(n=target, lt=[], idx=0):
if n == 0:
lt.sort()
if lt not in ans:#进行去重操作
ans.append(lt)
else:
for i in range(idx, len(candidates)):#因题目要求,每个数字只能用一次,所以每次只取后面的数字,进行寻找
if n < 0:
break
else:
#巧妙之处在于i+1,只有这样赋值,才是满足想法的程序,因为每次都去寻找后面的数字
find(n-candidates[i], lt+[candidates[i]], i+1)
find()
return ans
运行时间和内存使用:
- Runtime: 760 ms, faster than 5.73% of Python3 online submissions for Combination Sum II.
- Memory Usage: 14 MB, less than 6.52% of Python3 online submissions for Combination Sum II