【LeetCode】39. Combination Sum 解题报告(Python & C++)
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址:[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++)的更多相关文章
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [array] leetcode - 39. Combination Sum - Medium
leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...
- leetcode 39. Combination Sum 、40. Combination Sum II 、216. Combination Sum III
39. Combination Sum 依旧与subsets问题相似,每次选择这个数是否参加到求和中 因为是可以重复的,所以每次递归还是在i上,如果不能重复,就可以变成i+1 class Soluti ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- [LeetCode] 39. Combination Sum 组合之和
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), fin ...
- Java [Leetcode 39]Combination Sum
题目描述: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in ...
- LeetCode 39. Combination Sum (组合的和)
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique c ...
- 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 ...
- LeetCode 39 Combination Sum(满足求和等于target的所有组合)
题目链接: https://leetcode.com/problems/combination-sum/?tab=Description Problem: 给定数组并且给定一个target,求出所 ...
随机推荐
- perl中tr的用法(转载)
转载:http://blog.sina.com.cn/s/blog_4a0824490101hncz.html (1)/c表示把匹配不上的字符进行替换. $temp="AAAABCDEF&q ...
- vim 的使用
基本操作: 命令行模式 进入命令行 打开文本的时候,直接进去命令行模式 在其它模式按ESC,可以进入命令行模式 新建进入了命令行模式 光标进入末行"G"(shift+按键g,自学 ...
- Mysql笔记(3)
查询总数count(1)查询总和sum(数据名) 查询最大值max(数据名) 查询最小值min(数据名) 查询平均值avg(数据名) 去除重复 通过having来过滤group by字句的结果信息 i ...
- 深入理解mysql锁与事务隔离级别
一.锁 1.锁的定义 锁即是一种用来协调多线程或进程并发使用同一共享资源的机制 2.锁的分类 从性能上分类:乐观锁和悲观锁 从数据库操作类型上分类:读锁和写锁 从操作粒度上分类:表锁和行锁 2 ...
- day27 网络编程
1.OSI七层协议 1.七层划分为:应用层,表示层.会话层.传输层.网络层.数据链路层.物理层 2.五层划分:应用层.传输层.网络层.数据链路层.物理层 应用层: 表示层: 会话层: 传输层:四层交换 ...
- 【leetcode】170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
Design and implement a TwoSum class. It should support the following operations: add and find. add ...
- Linux:cut命令...未完待续
一.定义 正如其名,cut的工作就是"剪",具体的说就是在文件中负责剪切数据用的.cut是以每一行为一个处理对象的,这种机制和sed是一样的. 2.剪切依据 cut命令主要是接受三 ...
- Javaj基础知识runtime error
遇到的java 运行时错误: NullPointerException空指针 ,简单地说就是调用了未经初始化的对象或者是不存在的对象,这个错误经常出现在创建图片,调用数组这些操作中,比如图片未经初始 ...
- Orcale 数据加载
CSV 逗号分隔值格式文件 1,若要加载的文件不是CSV格式,可以修改数据文件,用分隔符来替换逗号:也可以修改控制文件,将FIELDS TERMINATED BY的值改为实际的分隔符. eg, 要向s ...
- Taro 3.5 canary 发布:支持适配 鸿蒙
一.背景 鸿蒙作为华为自研开发的一款可以实现万物互联的操作系统,一经推出就受到了很大的关注,被国人寄予了厚望.而鸿蒙也没让人失望,今年 Harmony2.0 正式推出供用户进行升级之后,在短短的三个月 ...