topic:
Given an array candidates with no duplicate elements and a target number target, find out all combinations of candidates that can make the number sum target.
The numbers in candidates can be repeatedly selected without limitation.
Description:
- All numbers (including target) are positive integers.
- The solution set cannot contain repeated combinations.
prompt:
- 1 <= candidates.length <= 30
- 1 <= candidates[i] <= 200
- Each element in the candidate is unique.
- 1 <= target <= 500
Example:
Input: candidates = [2,3,6,7], target = 7,
the solution set is:
[
[7],
[2,2,3]
]
source:
Problem-solving ideas: backtracking
Continue to learn the idea of backtracking. The difference from the previous two combinations is that this question 1) the array is not sorted, so it is sorted first; 2) the number can be reused, so the parameter is no longer +1 during recursion.
- Recursive termination condition: current sum is greater than or equal to target
- The result meets the condition: sum == target
- Pruning condition: the current sum is about to exceed the target value
c++ code:
class Solution {
public:
vector< vector<int> > result;
vector<int> path;
vector< vector<int> > combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end()); // 排序
back(candidates, target, 0, 0);
return result;
}
void back(const vector<int>& candidates, int target, int sum, int start) {
if (sum == target) {
result.push_back(path);
return;
}
for (int i = start; i < candidates.size(); i++) {
if (sum + candidates[i] > target) break; // 剪枝
path.push_back(candidates[i]);
sum += candidates[i];
back(candidates, target, sum, i); // 因为可以重复使用数字,所以i而不是i+1
sum -= candidates[i];
path.pop_back();
}
}
};