题目地址:[https://leetcode.com/problems/combination-sum/description/][1]

题目描述

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

题目大意

使用候选集的数字,能有多少种不同的组合,使得每个组合的和都是target。

解题方法

方法一:递归

使用递归解法,这个递归方法是,依次遍历每个元素,判断其与剩余数字的大小,如果比剩余target小,那么就放入到路径path中,并且,把剩余元素target减去当前元素。

理解递归最重要的当然是递归函数的定义:以index为起始元素,在candidates的index元素和其之后的元素中,抽取一定的元素,能否构成和为target的路径Path。

Python代码如下:

class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
self.dfs(candidates, target, 0, res, [])
return res def dfs(self, nums, target, index, res, path):
if target < 0:
return
elif target == 0:
res.append(path)
return
for i in xrange(index, len(nums)):
if nums[index] > target:
return
self.dfs(nums, target - nums[i], i, res, path + [nums[i]])

方法二:回溯法

上面的DFS虽说也是递归,但是和回溯还是有区别的。因为回溯的含义,此路不通就倒着走回去,而上面的DFS是进行了全集的搜索。

这个回溯还是很好写的,需要一个新的函数,含义是从候选集的start位置开始向后寻找和为target的路径。如果target等于0了就是我们终止的一个条件,即正好搜索到了一条合适的路径。

需要注意的是path后面的插入元素和弹出元素操作。向path中添加元素i后进行后面的搜索,搜索完之后说明i位置的所有结果都已经结束了,故向后退一步即弹出最后的元素。

另外就是题目允许每个数字使用多次,所以for循环开始的地方是start,而往回溯函数里面传递的i的也是start.

C++代码如下:

class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> path;
helper(candidates, 0, res, path, target);
return res;
}
void helper(vector<int>& candidates, int start, vector<vector<int>>& res, vector<int>& path, int target) {
if (target < 0) return;
if (target == 0) {
res.push_back(path);
}
for (int i = start; i < candidates.size(); ++i) {
path.push_back(candidates[i]);
helper(candidates, i, res, path, target - candidates[i]);
path.pop_back();
}
}
};

日期

2018 年 2 月 13 日
2018 年 12 月 19 日 —— 感冒了,好难受
2019 年 9 月 25 日 —— 做梦都在秋招,这个秋天有毒

【LeetCode】39. Combination Sum 解题报告(Python & C++)的更多相关文章

  1. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  2. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  3. leetcode 39. Combination Sum 、40. Combination Sum II 、216. Combination Sum III

    39. Combination Sum 依旧与subsets问题相似,每次选择这个数是否参加到求和中 因为是可以重复的,所以每次递归还是在i上,如果不能重复,就可以变成i+1 class Soluti ...

  4. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  5. [LeetCode] 39. Combination Sum 组合之和

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), fin ...

  6. Java [Leetcode 39]Combination Sum

    题目描述: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in  ...

  7. LeetCode 39. Combination Sum (组合的和)

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique c ...

  8. LeetCode: Minimum Path Sum 解题报告

    Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to b ...

  9. LeetCode 39 Combination Sum(满足求和等于target的所有组合)

    题目链接: https://leetcode.com/problems/combination-sum/?tab=Description   Problem: 给定数组并且给定一个target,求出所 ...

随机推荐

  1. perl和python3 同时打开两个文件

    perl : while(defined(my $f1=<FQ1>) && defined(my $f2=<FQ2>)){ condition } python ...

  2. 浅谈Facebook的服务器架构

    导读:毫无疑问,作为全球最领先的社交网络,Facebook的高性能集群系统承担了海量数据的处理,它的服务器架构一直为业界众人所关注.CSDN博主yanghehong在他自己最新的一篇博客< Fa ...

  3. Flink 实践教程-进阶(2):复杂格式数据抽取

    作者:腾讯云流计算 Oceanus 团队 流计算 Oceanus 简介 流计算 Oceanus 是大数据产品生态体系的实时化分析利器,是基于 Apache Flink 构建的具备一站开发.无缝连接.亚 ...

  4. PC端申请表

    公司项目需求中要做用html做一个PDF申请表的样式出来.有点意思,贴上来大家看看. 先上效果图: 附上源代码: HTML:<div id="form"> <h2 ...

  5. 带你全面了解 OAuth2.0

    最开始接触 OAuth2.0 的时候,经常将它和 SSO单点登录搞混.后来因为工作需要,在项目中实现了一套SSO,通过对SSO的逐渐了解,也把它和OAuth2.0区分开了.所以当时自己也整理了一篇文章 ...

  6. 利用python代码获取文件特定的内容,并保存为文档

    说明:有段时间需要读取上百个文件的单点能(sp),就写了下面的代码(计算化学狗努力转行中^-^) import os.path import re # 1 遍历指定目录,显示目录下的所有文件名 def ...

  7. RB-Tree深度探索

    关联式容器就是通过key值来寻找value,这个和数据库很相像,为了提升查找效率,因此关联式容器底层大多数用红黑树或哈希表来实现. 红黑树是高度平衡的二叉树,它也被称为平衡二元搜索树. 如上所示,正常 ...

  8. mysql index 8.0

    创建表 use vodb; drop table if exists test1; create table test1(id int NOT NULL AUTO_INCREMENT primary ...

  9. html块 布局

    可通过<div>和<span>将html元素组合起来. Html块元素 大多数html元素被定义为块级元素或内联元素. 块级元素在浏览器显示时,通常会以新行来开始(和结束).例 ...

  10. transient关键字和volatile关键字

    看到HashSet的源代码的时候,有一个关键字不太认识它..transient,百度整理之: Java的Serialization提供了一种持久化对象实例的机制,当持久化对象时,可能有一些特殊的对象数 ...