题目:
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is:
[7]
[2, 2, 3]
题意:
给定一个可供选择的set集合C和一个目标数字T,找到集合C中所有和为T的唯一的组合。
相同的数字可以无限次的被使用。
note:
1、所有的数字(包含target目标值)都是正整数;
2、所有的组合元素(a1, a2, … , ak)必须是单调递增的(ie, a1 ≤ a2 ≤ … ≤ ak).
3、返回的结果集中不包含重复的组合。
思路:
利用回溯法,迭代递归调用。先对candidates集合排序,保证集合的有序性,之后从第一个元素开始迭代判断是否能够等于target,等于的时候将组合好的cur放到result中。
按照以下顺序,先完成[2, 2, 3]组合,之后完成[7]
代码:16ms
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<vector<int>> result; vector<int> cur; combinationSum(candidates, target, result, cur, 0); return result; } private: void combinationSum(vector<int>& candidates, int target, vector<vector<int>>& result, vector<int>& cur, int begin){ if(!target){ result.push_back(cur); return; } for(int i=begin; i!=candidates.size() && target>=candidates[i]; ++i){ cur.push_back(candidates[i]); combinationSum(candidates, target-candidates[i], result, cur, i); cur.pop_back(); } } };