(98)39. Combination sum (leetcode)

题目链接:
https://leetcode-cn.com/problems/combination-sum/
难度:中等
39. 组合总和
	给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
	candidates 中的数字可以无限制重复被选取。
说明:
	所有数字(包括 target)都是正整数。
	解集不能包含重复的组合。 
示例 1:
	输入:candidates = [2,3,6,7], target = 7,	
	所求解集为:
	[
	  [7],
	  [2,2,3]
	]
示例 2:
	输入:candidates = [2,3,5], target = 8,
	所求解集为:
	[
  	  [2,2,2,2],
	  [2,3,3],
	  [3,5]
	]
提示:
	1 <= candidates.length <= 30
	1 <= candidates[i] <= 200
	candidate 中的每个元素都是独一无二的。
	1 <= target <= 500

It’s not difficult to backtrack + recursion without considering a lot of questions.
But I made a mistake when I wrote it. Record: Numbers can be reused. There are two cases to consider when recursing: 1. Use the number 2. Do not use this number,
but in the second case, note that pos does not need to be +1 because it can be reused
(ps: extremely low efficiency)

class Solution {
    
    
public:
    vector<vector<int>> ans;
    void dfs(int curtarget,vector<int>& candidates,int pos,vector<int> tmp){
    
    
        if(curtarget==0){
    
    
            ans.push_back(tmp);
            return;
        }
        if(pos==candidates.size()||curtarget<0){
    
    
            return;
        }
        dfs(curtarget,candidates,pos+1,tmp);
        tmp.push_back(candidates[pos]);
        dfs(curtarget-candidates[pos],candidates,pos,tmp);
        tmp.pop_back();
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    
    
        vector<int> tmp;
        dfs(target,candidates,0,tmp);
        return ans;
    }
};

Using pruning is not familiar with pruning,,, the writing is a bit ugly

class Solution {
    
    
public:
    
    void dfs(int curtarget, vector<int>& candidates, vector<int> &tmp, int begin, int len,vector<vector<int>>& ans) {
    
    
        if (curtarget == 0) {
    
    
            ans.push_back(tmp);
            return;
        }
        for (int i = begin; i < len; ++i) {
    
    
            int t=candidates[i];
            if (curtarget - t < 0) {
    
    
                break;
            }
            tmp.push_back(t);
            dfs(curtarget - t, candidates, tmp, i, len,ans);
            tmp.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    
    
        vector<int> tmp;
        vector<vector<int>> ans;
        sort(candidates.begin(), candidates.end());
        dfs(target, candidates, tmp, 0, candidates.size(),ans);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/li_qw_er/article/details/108483256