题目地址:[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. docker 使用加速器下载

    因为docker官网的镜像地址docker.hum.com是在国外的 所以下载速度比较慢,国内有一些镜像源是比较快的,内容是和docker官网的一致 常用的加速器有 docker-cn 阿里云加速器 ...

  2. ggplot2 图例及分页参数

    图例: 1 theme(legend.title =element_blank()) 2 guides(fill = guide_legend(title = NULL)) # 去掉图例title 3 ...

  3. 生产调优1 HDFS-核心参数

    目录 1 HFDS核心参数 1.1 NameNode 内存生产配置 问题描述 hadoop-env.sh中配置 1.2 NameNode 心跳并发配置 修改hdfs-site.xml配置 1.3 开启 ...

  4. mysql事务控制语言TCL

    Transaction Control Language 事务控制语言 事务:一个或一组sql语句组成一个执行单元,这个执行单元作为不可分割的整体执行.如果某个语句执行错误,整个单元回滚到最初的状态. ...

  5. acre, across

    acre The acre is a unit of land area used in the imperial and US customary systems. It is traditiona ...

  6. CSS基础语法(一)

    目录 CSS基础语法(一) 一.CSS简介 1.CSS语法规范 2.CSS代码风格 二.CSS基础选择器 1.标签选择器 2.类选择器 3.id选择器 4.通配符选择器 5.总结 三.CSS字体属性 ...

  7. 容器之分类与各种测试(四)——set

    set和multiset的去别在于前者的key值不可以重复,所以用随机数作为其元素进行插入时,遇到重复元素就会被拒绝插入(但是程序不会崩溃). 例程 #include<stdexcept> ...

  8. swift 实现QQ好友列表功能

    最近项目中有类似QQ好友列表功能,整理了一下,话不多说,直接上代码 import UIKit class QQFriend: NSObject { var name: String? var intr ...

  9. iBatis查询时报"列名无效"或"找不到栏位名称"无列名的错误原因及解决方法

    iBatis会自动缓存每条查询语句的列名映射,对于动态查询字段或分页查询等queryForPage, queryForList,就可能产生"列名无效".rs.getObject(o ...

  10. Output of C++ Program | Set 11

    Predict the output of following C++ programs. Question 1 1 #include<iostream> 2 using namespac ...