首页 技术 正文
技术 2022年11月12日
0 收藏 627 点赞 4,506 浏览 1080 个字

@author: ZZQ

@software: PyCharm

@file: combinationSum.py

@time: 2018/11/14 18:23

要求:给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。

解集不能包含重复的组合。

示例 1:

输入: candidates = [2,3,6,7], target = 7,

所求解集为:

[

[7],

[2,2,3]

]

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

思路:深搜+减枝

注意停止搜索:当和大于target时,结束该条支路的搜索。

注意去重:先对数组排好序,每次都处理当前元素以后的元素。

注意: 存入ans时需要将临时数组拷贝出来,否则ans中的答案会因为temp_ans的改变而一直改变。

import copy
class Solution():
def __init__(self):
pass def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
can_len = len(candidates)
if can_len == 0:
return []
ans = []
temp_ans = []
temp_sum = 0
start_index = 0
self.dfs(temp_ans, temp_sum, start_index, target, candidates, ans)
return ans def dfs(self, temp_ans, temp_sum, start_index, target, candidates, ans):
if temp_sum == target:
tt_ans = copy.deepcopy(temp_ans)
ans.append(tt_ans)
return
if temp_sum > target:
return
for i in range(start_index, len(candidates)):
temp_ans.append(candidates[i])
self.dfs(temp_ans, temp_sum + candidates[i], i, target, candidates, ans)
temp_ans.pop()
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,985
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,501
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,345
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,128
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,763
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,839