Leetcode 39 组合总和(回溯算法解题)

题目描述:

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取

来源:力扣(LeetCode)
链接: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 深度优先搜索算法

vector:  1. push_back()

      2. pop_back() 

上一篇:dfs --path sum 问题


下一篇:Invalid arguments ' Candidates are: #1 transform(#0, #0, #1, #2) #2 transform(#0, #0, #1, #2, #