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