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]
这道题是找出数组中相加和等于目标值的全部组合,题目难度为Medium。
下面代码的处理有一些缺陷,大家看完后可以看下第40题(传送门),里面的代码进行了更新。
比较典型的回溯法题目,采用深度优先的方法逐个加进数字比对,超过目标值就返回,否则继续加入新的数字递归遍历,和目标值相等时把当前结果加入返回值中。对回溯法还不太熟悉的同学可以先回顾下第51题(传送门)八皇后问题。
由于数字可以重复使用,最初在递归的循环中每次循环都从数组头部开始重新遍历,可惜超时了。为了提速,没有一开始就把数组排序,而是在找到结果后单独对结果排序,这样勉强通过了测试,但是效率很低。看了别人的代码才发现效率低的原因,原来好多人都没有查重!在每次循环中都从当前位置开始继续往后遍历,这样也保证了数字可以重复使用。但是题目没有说原始数组中没有重复元素啊,如果原始数组是[2,2,3,6,7],target=7,这样结果中会有重复的组合,可能题目说数字可以无限次使用暗示着数组不存在重复元素吧。。大家面试的时候最好问清楚。这里就不列出最初包含查重的代码了。具体代码:
class Solution {
void getSum(const vector<int>& candidates, int target, vector<vector<int>>& rst, vector<int>& curRst, int sum, int idx) {
if(sum == target) {
rst.push_back(curRst);
}
else {
for(int i=idx; i<candidates.size(); ++i) {
if(sum + candidates[i] > target) return;
curRst.push_back(candidates[i]);
getSum(candidates, target, rst, curRst, sum+candidates[i], i);
curRst.pop_back();
}
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> rst;
vector<int> curRst;
sort(candidates.begin(), candidates.end());
getSum(candidates, target, rst, curRst, 0, 0);
return rst;
}
};