问题描述
给定一个 无重复元素 的数组 candidates 和一个目标数 target,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
- 所有数字(包括 target )都是正整数。
- 解集不能包含重复的组合。
示例1:
输入: candidates = [2, 3, 6, 7],target = 7
所求解集为:[ [2, 2, 3], [7] ]
示例2:
输入: candidates = [2, 3, 5], target = 8
所求解集为: [ [2, 2, 2, 2], [2, 3, 3], [3, 5] ]
解决方法
思路
基本思路是采用回溯法进行搜索。
在回溯之前,我们先明确 candidates 数组的范围,即去除值大于 target 的部分。
程序实现
class Solution {
private:
vector<vector<int>> res;
vector<int> ans;
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
int left = 0, right = 0;
for (; right < candidates.size() && candidates[right] <= target; right++);
backtrack(candidates, left, right == candidates.size() ? right - 1 : right, target);
return res;
}
private:
void backtrack(vector<int>& candidates, int left, int right, int target) {
if (target < 0) return;
if (! target) {
res.push_back(ans);
return;
}
for (int i = left; i <= right && candidates[i] <= target; i++) {
ans.push_back(candidates[i]);
backtrack(candidates, i, right, target - candidates[i]);
ans.pop_back();
}
}
};
@北京·海淀 2019.04.22