• [LeetCode]题解(python):040-Combination Sum II


    题目来源:

      https://leetcode.com/problems/combination-sum-ii/


    题意分析:

      给定一个数组序列和一个target。给出数组里面可以相加等于target的所有组合,数组里面的数每个最多出现一次。1.题目中所有的数都是正数,2.组合的答案必须按字典序排序,3.每个组合只出现一次。


    题目思路:

      这题和上一题类似,首先将数组排序,如果组合不包括第一个数,那么,直接跳到和第一个数不等的数,如果包括,那么数组跳到下一个数,target 减去第一个数。


    代码(python):

      

     1 class Solution(object):
     2     def boolcombinationSum(self, candidates, target,j):
     3         ans = [];size = len(candidates)
     4         if target == 0:
     5             return []
     6         if size < j + 1 or target < 0:
     7             return [[-1]]
     8         n = 1
     9         while j + n < size:
    10             if candidates[j + n] != candidates[j]:
    11                 break
    12             n += 1
    13         tmp1 = self.boolcombinationSum(candidates,target,j + n)
    14         tmp2 = self.boolcombinationSum(candidates,target - candidates[j],j + 1)
    15         if len(tmp2) == 0:
    16             ans.append([candidates[j]])
    17         elif tmp2 != [[-1]]:
    18             for i in range(len(tmp2)):
    19                 ans.append([candidates[j]] + tmp2[i])
    20         if len(tmp1) != 0 and tmp1 != [[-1]]:
    21             for i in range(len(tmp1)):
    22                 ans.append(tmp1[i])
    23         if len(tmp2) != 0 and tmp1 == [[-1]] and tmp2 == [[-1]]:
    24             return [[-1]]
    25         return ans
    26     def combinationSum2(self, candidates, target):
    27         """
    28         :type candidates: List[int]
    29         :type target: int
    30         :rtype: List[List[int]]
    31         """
    32         candidates.sort()
    33         ans = self.boolcombinationSum(candidates,target,0)
    34         if ans == [[-1]]:
    35             return []
    36         return ans
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4934155.html

  • 相关阅读:
    转:Windows 7下安装CentOS双系统
    STL学习总结之<迭代器>
    转:linux静态库与动态库
    指向类成员和成员函数的指针
    STL学习总结之<仿函数>
    转:Linux Crontab 定时任务 命令详解
    转: 解决 Redhat 出现”This system is not registered with RHN”更新
    IOS 判断设备屏幕尺寸、分辨率
    IOS 文件管理共通函数整理
    IOS 编译ffmpeg For SDK6.1,模拟器、armv7、armv7s均可使用
  • 原文地址:https://www.cnblogs.com/chruny/p/4934155.html
Copyright © 2020-2023  润新知