Subject description:
Given a non-repeating array element candidates and a target number target, you can find all the candidates for the target numbers and combinations thereof.
Digital candidates may be selected without limitation repeated
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/combination-sum
class Solution { private: vector<vector <int>> results; vector<int> solution; public: void backtracking(vector<int> candidates, int target, int start){ if(target < 0) return; if(target == 0){ results.push_back(solution); return; } for(int i=start; i<candidates.size() && candidates[i]-target<=0; i++){ solution.push_back(candidates[i]); backtracking(candidates, target-candidates[i], i); solution.pop_back(); } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { std::sort(candidates.begin(), candidates.end()); backtracking(candidates, target, 0); return results; } };
DFS depth-first search algorithm
vector: 1. push_back()
2. pop_back()