首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【leetcode刷题】20T21-组合总和

【leetcode刷题】20T21-组合总和

作者头像
木又AI帮
发布2020-02-25 12:14:38
发布2020-02-25 12:14:38
3810
举报
文章被收录于专栏:木又AI帮木又AI帮

木又同学2020年第21篇解题报告

leetcode第39题:组合总和

https://leetcode-cn.com/problems/combination-sum


【题目】

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

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

说明:

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

代码语言:javascript
复制
示例 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]
]

【思路】

本题我暂时只想到暴力破解的方法,就是对于每种可能,再遍历数组candidate的元素,如果新组成的数组元素之和等于target,则加入到结果集中;如果大于target,则忽略;如果小于target,则添加至可能的集合中。最后,对结果集去重。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        tmp = [[ci] for ci in candidates if ci <= target]
        while len(tmp) > 0:
            sum_t = sum(tmp[0])
            if sum_t == target:
                res.append(str(sorted(tmp.pop(0))))
                continue

            # 遍历元素,观察相加是否<=target
            for ci in candidates:
                if sum_t + ci <= target:
                    t = copy.copy(tmp[0])
                    t.append(ci)
                    tmp.append(t)
                else:
                    break
            tmp.pop(0)
        res = list(set(res))
        res = [eval(si) for si in res]
        return res
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-02-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档