【LeetCode】39. Combination Sum(C++)
阿新 • • 發佈:2018-12-02
地址:https://leetcode.com/problems/combination-sum/
題目:
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:
Example 2:
理解:
本題需要尋找給定集合中哪些子集的和等於target
。雖然原來的集合沒有重複元素,但是元素是可以重複利用的。
基本思想,取集合中的一個元素candidates[i]
,然後判斷剩下的集合元素能否構成target-candidates[i]
。注意剩下的集合是可以包含candidates[i]
實現:
Accepted 16ms c++ solution use backtracking, easy understand.
這種實現使用排序避開了需要遍歷完整個集合。
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<vector<int>> res; vector<int> combination; combinationSum(candidates, target, res, combination, 0); return res; } private: void combinationSum(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& combination, 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]); combinationSum(candidates, target - candidates[i], res, combination, i); combination.pop_back(); } } };