# 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】背包问题

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

• ### 打卡群刷题总结0825——括号生成

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

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

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

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

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

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

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