专栏首页Petrichor的专栏leetcode: 40. Combination Sum II

leetcode: 40. Combination Sum II

Problem

# coding=utf-8

# Given a collection of candidate numbers (C) and a target number (T),
# find all unique combinations in C where the candidate numbers sums to T.
# 
# Each number in C may only be used once in the combination.
# 
# Note:
# All numbers (including target) will be positive integers.
# Elements in a combination (a1, a2, ... , ak) must be in non-descending order. 
# (ie, a1 <= a2 <= ... <= ak).
# The solution set must not contain duplicate combinations.
#
# For example, given candidate set 10,1,2,7,6,1,5 and target 8, 
# A solution set is: 
# [1, 7] 
# [1, 2, 5] 
# [2, 6] 
# [1, 1, 6]

AC

# DFS
class Solution():
    def combinationSum2(self, x, target):
        x.sort()
        res = []
        self.dfs(res, x, target-0, 0, [])
        return res
    def dfs(self, res, x, diff, start, path):
        if diff == 0 and path not in res:   # 加上 path not in res 来去重
            res.append(path)
        elif diff > 0:
            for j in range(start, len(x)):
                # 改为 self.dfs(res, x, diff-x[j], j, path+[x[j]]) 则 子数组 内 可含有 下标相同的元素
                self.dfs(res, x, diff-x[j], j+1, path+[x[j]])



if __name__ == "__main__":
    assert Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8) == [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • leetcode: 39. Combination Sum

    JNingWei
  • 【leetcode】背包问题

    完全背包的特点恰是每种物品可选无限件,所以就可以并且必须采用 w = W[i]…carry 的顺序循环:

    JNingWei
  • leetcode: 77. Combinations

    JNingWei
  • python慢画炫彩圆圈_pygame绘画与动画

    公众号---人生代码
  • 打卡群刷题总结0825——括号生成

    链接:https://leetcode-cn.com/problems/generate-parentheses

    木又AI帮
  • Python3 的面向对象

    用户2337871
  • 在MongoDB中使用聚合操作筛选与修改字段

    “$match”可以筛选出需要的记录,那么如果想只返回部分字段,又应该怎么做呢?这时就需要使用关键字“$project”。

    青南
  • 【python-leetcode107-树的宽度遍历】二叉树的层次遍历Ⅱ

    给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

    绝命生
  • 封装,封装的原理,Property ,setter ,deleter

    py3study
  • python手机号前7位归属地爬虫代码实例

    项目上需要用到手机号前7位,判断号码是否合法,还有归属地查询。旧的数据是几年前了太久了,打算用python爬虫重新爬一份

    砸漏

扫码关注云+社区

领取腾讯云代金券