本文共 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:
target
) will be positive integers.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(); } }};
回溯法(英语:backtracking)是中的一种。
对于某些计算问题而言,回溯法是一种可以找出所有(或一部分)解的一般性算法,尤其适用于约束满足问题(在解决约束满足问题时,我们逐步构造更多的候选解,并且在确定某一部分候选解不可能补全成正确解之后放弃继续搜索这个部分候选解本身及其可以拓展出的子候选解,转而测试其他的部分候选解)。
在经典的教科书中,展示了回溯法的用例。(八皇后问题是在标准国际象棋棋盘中寻找八个皇后的所有分布,使得没有一个皇后能攻击到另外一个。)
回溯法采用的思想,它尝试分步的去解决一个问题。在分步解决问题的过程中,当它通过尝试发现现有的分步答案不能得到有效的正确的解答的时候,它将取消上一步甚至是上几步的计算,再通过其它的可能的分步解答再次尝试寻找问题的答案。回溯法通常用最简单的方法来实现,在反复重复上述的步骤后可能出现两种情况:
在最坏的情况下,回溯法会导致一次为的计算。
转载地址:http://agtuz.baihongyu.com/