LeetCode 39. Combination Sum

Question link

LeetCode 39. Combination Sum

Topic Analysis

Given a set of numbers and a target value, the sum is the combination of target values.

Problem solving ideas

A result like this requires returning all the questions that meet the requirements to be solved. Nine times out of ten, recursion is used, and the idea of ​​solving the problem is similar. It can be found that these questions are all a routine, and they all need to write another recursive function. .

Add three variables to the recursive function, start records the current recursive subscript, answer is a combined solution, res saves all the solutions that have been obtained, each time a new recursive function is called, the target at this time is subtracted from the current array the number of.

Note that the original array needs to be sorted first to avoid duplication.

Reference Code

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector< vector<int> > res;
        vector<int> answer;
        sort(candidates.begin(), candidates.end());
        solve(candidates, target, res, answer, 0);
        return res;
    }
    
    void solve(vector<int>& candidates, int target, vector< vector<int> >& res, vector<int>& answer, int start) {
        if(target < 0) return;
        else if(target == 0) res.push_back(answer);
        else {
            for(int i = start; i < candidates.size(); i++) {
                answer.push_back(candidates[i]);
                solve(candidates, target-candidates[i], res, answer, i);
                answer.pop_back();
            }
        }
    }
};

similar topics


Summary of LeetCode All in One solutions (continuously updated...)

The copyright of this article belongs to the author AlvinZH and Blog Park. Reprinting and commercial use are welcome, but this statement must be retained without the author's consent, and a link to the original text should be given in an obvious position on the article page, otherwise the right to pursue legal responsibility is reserved.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324841863&siteId=291194637