zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Combination Sum II(组合和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]
    ]
    思路

       这道题的思路和前一道组合数的思路都是类似的,只不过在细节处理上不同。详细思路见代码
    解决代码

     1 class Solution(object):
     2     def combinationSum2(self, nums, target):
     3         """
     4         :type candidates: List[int]
     5         :type target: int
     6         :rtype: List[List[int]]
     7         """
     8         if len(nums) < 1:    # nums为空直接返回
     9             return []
    10         nums.sort()          # 对nums进行排序,主要目的是为了较少递归次数。
    11         res =[]
    12         self.get_res(nums, target, [], res) # 递归
    13         return res
    14     
    15     def get_res(self, nums, target, path, res):
    16         if target == 0:        # 结束条件,找到满足的组合将其添加进res列表中
    17             res.append(path)
    18             return
    19         if target < 0:        # 没有满足的组合直接返回
    20             return
    21         for i in range(len(nums)):    # 从第下标0开始寻找
    22             if i > 0 and nums[i] == nums[i-1]:    # 如果当前下小标元素和前一个相等直接跳过,避免产生相同的组合。
    23                 continue
    24             if nums[i] > target:         # 当前下标直接大于target,后面的元素都不会满足直接返回。
    25                 break
    26             self.get_res(nums[i+1:], target-nums[i], path+[nums[i]], res)  # 下一次递归时,都将nums大小减一。意味着从下一个开始重新寻找满足条件的组合
    27         
  • 相关阅读:
    初识分布式计算:从MapReduce到Yarn&Fuxi
    日志的艺术(The art of logging)
    关于负载均衡的一切:总结与思考
    打印中文dict list的各种姿势
    不想再被鄙视?那就看进来! 一文搞懂Python2字符编码
    什么是分布式系统,如何学习分布式系统
    再论分布式事务:从理论到实践
    从银行转账失败到分布式事务:总结与思考
    git命令
    IntelliJ idea 中使用Git
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10695247.html
Copyright © 2011-2022 走看看