题目地址:[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:

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

Example 2:

  1. Input: candidates = [2,3,5], target = 8,
  2. A solution set is:
  3. [
  4. [2,2,2,2],
  5. [2,3,3],
  6. [3,5]
  7. ]

题目大意

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

解题方法

方法一:递归

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

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

Python代码如下:

  1. class Solution(object):
  2. def combinationSum(self, candidates, target):
  3. """
  4. :type candidates: List[int]
  5. :type target: int
  6. :rtype: List[List[int]]
  7. """
  8. res = []
  9. candidates.sort()
  10. self.dfs(candidates, target, 0, res, [])
  11. return res
  12. def dfs(self, nums, target, index, res, path):
  13. if target < 0:
  14. return
  15. elif target == 0:
  16. res.append(path)
  17. return
  18. for i in xrange(index, len(nums)):
  19. if nums[index] > target:
  20. return
  21. 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++代码如下:

  1. class Solution {
  2. public:
  3. vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
  4. vector<vector<int>> res;
  5. vector<int> path;
  6. helper(candidates, 0, res, path, target);
  7. return res;
  8. }
  9. void helper(vector<int>& candidates, int start, vector<vector<int>>& res, vector<int>& path, int target) {
  10. if (target < 0) return;
  11. if (target == 0) {
  12. res.push_back(path);
  13. }
  14. for (int i = start; i < candidates.size(); ++i) {
  15. path.push_back(candidates[i]);
  16. helper(candidates, i, res, path, target - candidates[i]);
  17. path.pop_back();
  18. }
  19. }
  20. };

日期

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. mysql-计算排名

    mysql计算排名,获取行号rowno 学生成绩表数据 SELECT * FROM table_score ORDER BY score DESC; 获取某个学生成绩排名并计算该学生和上一名学生成绩差 ...

  2. Perl if条件判断

    Perl 条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 条件判断常用: True         #布尔值 not True   #布尔值 ! True    ...

  3. 从零构建Java项目(Maven+SpringBoot+Git) #02 奥斯丁项目

    前两天我说要写个项目来持续迭代,有好多小伙伴都表示支持和鼓励,项目的第一篇这不就来了么~我给项目取了个名字,英文名叫做:austin,中文名叫做:奥斯丁 名字倒没有什么特别的含义,我单纯觉得这个名字好 ...

  4. Shell 统计文件的行数

    目录 统计文件的行数 题目 题解-awk 题解-wc 题解sed 统计文件的行数 题目 写一个 bash脚本以输出一个文本文件 nowcoder.txt中的行数 示例: 假设 nowcoder.txt ...

  5. 虚拟机中安装centos系统的详细过程

    linux-centos的安装 检查电脑是否开启虚拟化,只有开启虚拟化才能安装虚拟机 新建虚拟机 鼠标点进去,选中红框所示,回车 登录: 输入默认用户名(超级管理员 root) 密码:安装时设置的密码

  6. 零基础学习java------38---------spring中关于通知类型的补充,springmvc,springmvc入门程序,访问保护资源,参数的绑定(简单数据类型,POJO,包装类),返回数据类型,三大组件,注解

    一. 通知类型 spring aop通知(advice)分成五类: (1)前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常. (2)正常返回通知 ...

  7. openwrt编译ipk包提示缺少feeds.mk文件

    问题具体表现如下 这个问题困扰了我两个多星期,总算解决了.解决方案如下: 首先,先应该把配置菜单调好. 我的硬件是7620a,要编译的ipk包为helloworld,所以应该使用 make menuc ...

  8. Oracle——概要文件profile

    profile文件详解 一.目的         Oracle系统中的profile可以用来对用户所能使用的数据库资源进行限制,使用Create Profile命令创建一个Profile,用它来实现对 ...

  9. Linux基础命令---dig工具

    dig dig是一个DNS查询工具,多数管理员会使用dig命令来解决DNS的问题. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.   1.语法       di ...

  10. Linux运维实战之磁盘分区、格式化及挂载(一)

    在网络系统中,磁盘和文件系统管理是两个非常基本.同时也是非常重要的管理任务,特别是文件系统管理,因为它与用户权限和整个网络系统的安全息息相关.本次博文的主题是关于Linux系统中磁盘分区.格式化及挂载 ...