给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

示例 2:输入: candidates = [2,5,2,1,2], target = 5,所求解集为:

[
  [1,2,2],
  [5]
] 解题思路类似上一题,
不同之处是这道题不允许重复使用candidates中的元素。
我们可以直接在上一道题目的代码上修改,递归的时候将 idx 加 1(需判断是否超出candidates的范围),另外由于题目输入的candidates可能包含相同的元素,所以我们需要对得到的答案进行去重处理。 代码如下:
class Solution:
def Slover(self, candidates, target, res, path, idx):
for i in range(idx, len(candidates)):
new_target = target - candidates[i]
if new_target < 0:
return
else:
if new_target == 0:
res.append(path + [candidates[i]])
else:
idx = idx + 1
if idx < len(candidates):
self.Slover(candidates, new_target, res, path + [candidates[i]], idx)
else:
return def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
path = []
idx = 0
candidates = sorted(candidates)
self.Slover(candidates, target, res, path, idx)
ud_res = []
for r in res:
if r not in ud_res:
ud_res.append(r)
return ud_res
 

最新文章

  1. java 线程安全 Lock
  2. C字符数组赋值(转)
  3. c++ for_each()与仿函数
  4. [leetcode]_Best Time to Buy and Sell Stock I &amp;&amp; II
  5. 在ubuntu16.04 下安装haproxy 1.5.11 做tcp负载均衡
  6. [转]Windows Shell 编程 第九章 【来源:http://blog.csdn.net/wangqiulin123456/article/details/7987969】
  7. [iOS Animation]-CALayer 图层性能
  8. SpringMVC(二)--处理数据模型、ModelAndView、Model、Map、重定向、@ModelAttribute、
  9. WebApi的多版本管理
  10. Android相关面试题---初识
  11. TensorRT&amp;Sample&amp;Python[uff_custom_plugin]
  12. 使用Node.js搭建数据爬虫crawler
  13. 原生JavaScript中动画与特效的实现原理
  14. sparkSQL将谓词推入kudu引擎
  15. Vue + Element UI 实现权限管理系统 前端篇(十二):用户管理模块
  16. GCC 用户态&amp;内核态 Makefile
  17. Codeforces 798D Mike and distribution - 贪心
  18. [原][osgEarth][JSBSim]重新整理使用JSBSim飞机动力模拟的使用
  19. Weighted Channel Dropout for Regularization of Deep Convolutional Neural Network
  20. CSS3实战之box-sizing

热门文章

  1. BottomNavigationBar使用详解
  2. python记录_day13 内置函数
  3. linux安装curl扩展
  4. 基本数据类型list,tuple
  5. sublime ctags跳转函数使用
  6. Windows与Linux的回车换行转换
  7. thinkphp 3.2 加载第三方库 第三方命名空间库
  8. axios 参数为payload的解决方法
  9. owin启动事项
  10. chrome console 阻止 Navigated to