Leetcode brushing notes 39. Combination sum

39. Combined Sum


Time: September 9, 2020
Knowledge point: Backtracking
Topic link: https://leetcode-cn.com/problems/combination-sum/

Question
Given an array candidates without repeating elements and a target number target, find all combinations in candidates that make the sum of numbers target.

The numbers in candidates can be selected repeatedly without limit.

illustrate:

All numbers (including target) are positive integers.
The solution set cannot contain duplicate combinations.

Example 1
input :
candidates = [2,3,6,7], target = 7,
output :

[
  [7],
  [2,2,3]
]

Example 2
input :
candidates = [2,3,5], target = 8,
output :

[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

solution

  1. Similar to 77. Combinations and N Queens
  2. Backtracking out of the condition: the size in the solution is equal to the target
  3. The numbers put in backtracking: the latter is greater than or equal to the former, use now_id to store the subscript, and traverse from now_num

code

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
    
    
public:
    vector<vector<int>> ans;
    vector<int> tmp;
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    
    
        dfs(0,target,0,candidates);
        return ans;
    }
    void dfs(int now_id,int target,int now_sum,vector<int> &candidates){
    
    
        if(now_sum > target){
    
    return;}
        if(now_sum==target){
    
    
            ans.push_back(tmp);
            return ;
        }
        for(int i=now_id;i<candidates.size();i++){
    
    
            now_sum += candidates[i];
            tmp.push_back(candidates[i]);
            dfs(i,target,now_sum,candidates);
            tmp.pop_back();
            now_sum -= candidates[i];
        }
    }
};
int main()
{
    
    
    vector<int> candidates{
    
    2,3,5};
    int target = 8;
    Solution s;
    vector<vector<int>> ans = s.combinationSum(candidates, target);
    for(int i=0;i<ans.size();i++){
    
    
        for(int j=0;j<ans[i].size();j++){
    
    
            if(j!=0)    cout<<",";
            cout<<ans[i][j];
        }
        cout<<endl;
    }
    return 0;
}

Today is also a day to love zz!

Guess you like

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