博客
关于我
39. Combination Sum
阅读量:420 次
发布时间:2019-03-06

本文共 1964 字,大约阅读时间需要 6 分钟。

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]]

 

AC code:

class Solution {public:    vector
> combinationSum(vector
& candidates, int target) { vector
> res; vector
combination; sort(candidates.begin(), candidates.end()); backtracking(candidates, res, combination, target, 0); return res; } void backtracking(vector
& candidates, vector
>& res, vector
& combination, int target, int begin) { if (!target) { res.push_back(combination); return; } for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) { combination.push_back(candidates[i]); backtracking(candidates, res, combination, target-candidates[i], i); combination.pop_back(); } }};

 

Runtime: 
12 ms, faster than 61.39% of C++ online submissions for Combination Sum.

 

回溯法英语:backtracking)是中的一种。

对于某些计算问题而言,回溯法是一种可以找出所有(或一部分)解的一般性算法,尤其适用于约束满足问题(在解决约束满足问题时,我们逐步构造更多的候选解,并且在确定某一部分候选解不可能补全成正确解之后放弃继续搜索这个部分候选解本身及其可以拓展出的子候选解,转而测试其他的部分候选解)。

在经典的教科书中,展示了回溯法的用例。(八皇后问题是在标准国际象棋棋盘中寻找八个皇后的所有分布,使得没有一个皇后能攻击到另外一个。)

回溯法采用的思想,它尝试分步的去解决一个问题。在分步解决问题的过程中,当它通过尝试发现现有的分步答案不能得到有效的正确的解答的时候,它将取消上一步甚至是上几步的计算,再通过其它的可能的分步解答再次尝试寻找问题的答案。回溯法通常用最简单的方法来实现,在反复重复上述的步骤后可能出现两种情况:

  • 找到一个可能存在的正确的答案
  • 在尝试了所有可能的分步方法后宣告该问题没有答案

在最坏的情况下,回溯法会导致一次为的计算。

 

转载地址:http://agtuz.baihongyu.com/

你可能感兴趣的文章
C++高精度模板
查看>>
错题重错之WYT的刷子 单调队列
查看>>
联赛模拟测试23 D. 真相 思维题
查看>>
牛顿迭代学习笔记
查看>>
Scala中的空
查看>>
设计模式学习笔记(二十三:解释器模式)
查看>>
Databricks 第4篇:pyspark.sql 分组统计和窗口
查看>>
SSISDB2:SSIS工程的操作实例
查看>>
业务工作流平台设计(七)
查看>>
业务工作流平台设计(八)
查看>>
大视角、大方向、大问题、大架构:(二)应用的相关问题
查看>>
SpringBoot Web(SpringMVC)
查看>>
javascript 之对象-13
查看>>
解决:angularjs radio默认选中失效问题
查看>>
java按照关键字指定的key删除redis(支持模糊删除)
查看>>
Jmeter-ForEach控制器
查看>>
windows环境下安装zookeeper(仅本地使用)
查看>>
Docker学习(十三)- docker rm 命令详解
查看>>
解决Eclipse左键无法查看maven第三方包的源代码,多图亲测可用【转】
查看>>
selnium远程机上传图片遇到的坑
查看>>