39. Combination sum (backtracking)

Given an array of candidates with no duplicate elements and a target number target, find out all combinations of candidates that can make the sum of numbers target.

The numbers in candidates can be repeatedly selected without limitation.

Description:

All numbers (including target) are positive integers.
The solution set cannot contain repeated combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,
the solution set is:
[
[7],
[2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
the solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

analysis:

Backtracking is used for combination problems. The step is to write a backtracking function, first determine when to get a useful combination push to the solution set, under what circumstances can exit early to achieve the purpose of pruning, and then use a for loop to simulate the push from top to bottom. Then recursively call the backtracking function to select the next layer of nodes, and then simulate the backtracking process through pop.
ps: Compared with the most basic combination problem, this question is different in that the elements can be reused, so when backtracking is recursive, i is passed in instead of i+1

class Solution {
    
    
public:
    vector<vector<int>> ret;
    vector<int> path;
    void backtracking(vector<int>& candidates, int target, int index){
    
    
        if(target == 0){
    
    
            ret.push_back(path);
            return;
        }
        // 剪枝的操作要放在递归的外面,要不然成剪根操作了
        if(target < 0) return;
        for(int i = index; i < candidates.size(); i++){
    
    
            target -= candidates[i];
            path.push_back(candidates[i]);
            // 把index用i传入,然后再下一个for循环的开始让i = index
            // 从而不会出现重复的组合
            backtracking(candidates, target, i);
            target += candidates[i];
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    
    
        backtracking(candidates, target, 0);
        return ret;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/113859752