LeetCode算法题之40. Combination Sum II(medium)

题目描述:

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,每个数只能用一次

解题思路:

  1. 因为有了之前的想法,所以这次完全可以思路照搬
  2. 区别就在于用程序实现每次寻找的数,是没有用过的数字,其余判定条件是一样的
  3. 具体操作就是让程序用循环每次去找那个数后面的数,看有没有符合条件的
  4. 此句话给自己,若想真明白,需花时间,下功夫,把每一个变量到底是怎样变化弄清楚

少废话,上代码:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值