Given a number of columns (unordered) and a target value, we can find all possible combinations and combinations equal to or equal to the target value. The number in the array can be reused.
Algorithm concept: recursion.
- Sorts arrays from small to large;
- Make I = start subscript (initial 0), for each number,
- If the value is equal to the target value, add the value to the cache result and add the cached result to the output queue. Then, delete the value from the cache result;
- If it is smaller than the target value, add this number to the cache result and call this algorithm recursively. The target value is updated to the difference value and the start subscript is I;
- If it is greater than the target value, the algorithm returns.
Understanding of 2.2: If this number is smaller than the target value, because the algorithm is cyclic recursion, the initial subscript must not be smaller than I (otherwise, repetition occurs ).
Code:
1 class Solution { 2 public: 3 vector<vector<int> > combinationSum(vector<int> &candidates, int target) { 4 vector<int> A(candidates); 5 vector<int> oneRes; 6 vector<vector<int> > result; 7 sort(A.begin(), A.end()); 8 helper(A, target, oneRes, result, 0); 9 return result;10 }11 12 void helper(vector<int> A, int target, vector<int> &oneRes, vector<vector<int> > &result, int start) {13 for (int i = start; i < A.size(); i++) {14 if (A[i] == target) {15 oneRes.push_back(A[i]);16 result.push_back(oneRes);17 oneRes.pop_back();18 }19 else if (A[i] < target) {20 oneRes.push_back(A[i]);21 helper(A, target-A[i], oneRes, result, i);22 oneRes.pop_back();23 }24 else return;25 }26 }27 };
[Leetcode series] combination and enumeration problems