博客
关于我
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/

你可能感兴趣的文章
(数据科学学习手札27)sklearn数据集分割方法汇总
查看>>
阿里巴巴Json工具-Fastjson教程
查看>>
Spring security OAuth2.0认证授权学习第二天(基础概念-RBAC)
查看>>
PySide图形界面开发(一)
查看>>
882. Reachable Nodes In Subdivided Graph
查看>>
375. Guess Number Higher or Lower II
查看>>
41. First Missing Positive
查看>>
80. Remove Duplicates from Sorted Array II
查看>>
83. Remove Duplicates from Sorted List
查看>>
410. Split Array Largest Sum
查看>>
程序员视角:鹿晗公布恋情是如何把微博搞炸的?
查看>>
系统编程-进程间通信-无名管道
查看>>
一个支持高网络吞吐量、基于机器性能评分的TCP负载均衡器gobalan
查看>>
404 Note Found 团队会议纪要
查看>>
使用Redis作为Spring Security OAuth2的token存储
查看>>
【SOLVED】Linux使用sudo到出现输入密码提示延迟时间长
查看>>
springmvc转springboot过程中访问jsp报Whitelabel Error Page错误
查看>>
项目引入非配置的文件,打成war包后测试报错的可能原因
查看>>
Git学习笔记
查看>>
不需要爬虫也能轻松获取 unsplash 上的图片
查看>>