C ++ algorithm: 2 ----- Total composition conditions recursive backtracking

topic:

Given an array of candidates and the number one goal target, you can find all the candidates for the target numbers and combinations. Each number candidates used only once in each combination.
Note: All figures (including the target number) are positive integers. Solution Set can not contain duplicate combinations thereof.

Example 1

: Input: candidates = [10,1,2,7,6,1,5], target = 8, the set is solved: [[1, 7], [1, 2, 5], [2, 6] , [1, 1, 6]]

Thinking;

Adding a title on the basis of the previous determination if (i> start && candidates [i-1] == candidates [i]) continue;

Code:


//思路;在前一题基础上加上判断if(i>start&&candidates[i-1]==candidates[i])  continue;
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        
        vector<vector<int>> ret;
        vector<int> temp;
        
        sort(candidates.begin(), candidates.end());
        
        search_combine(candidates, temp, ret, target, 0, 0);
        
        return ret;
    }
    
private:
    void search_combine(vector<int>& candidates, vector<int> temp, vector<vector<int>>& ret, int& target, int count, int start){
        if(count == target)
        {
            ret.push_back(temp);
            
            return ;
        }
        else if(count > target)
            return ;
        else
        {
            for(int i = start; i < candidates.size(); i++)
            {
                if(i>start&&candidates[i-1]==candidates[i])
                    continue;
                
                temp.push_back(candidates[i]);
                count += candidates[i];
                search_combine(candidates, temp, ret, target, count, i+1);
                temp.erase(temp.end()-1);
                count -= candidates[i];
            }
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_31820761/article/details/90951123