39. 组合总和

题目描述

Given a set of candidate numbers ( C ) and a target number ( T ),find all unique combinations in C where the candidate numbers sums to T .The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.Elements in a combination (a 1, a 2, … , a k) must be in non-descending order(非降序,即升序). (ie, a1 ≤ a2 ≤ … ≤ a k).The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7, A solution set is:

[7]
[2, 2, 3]

思路

前缀+一个元素,一层一层的产生,同一前缀加一个不同的元素,不同前缀之间由于前缀不同自然加同一个元素产生的一定不同

代码实现

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {

    	vector<vector<int>> ret;
    	sort(candidates.begin(),candidates.end());
        //显然我们不能使用原候选集合作为临时结果集合,所以这里需要我们自己定义
    	vector<int> temp;
    	int curSum = 0;
    	combinationSumCore(candidates,0,ret,temp,curSum,target);
    	return ret;        
    }


    void combinationSumCore(vector<int> &candidates,int start,vector<vector<int>> &ret,vector<int> &temp,int &curSum,int target)
    {
        //这里的程序设计保证在进入递归函数时curSum一定没有达到目标
    	for(int i = start;i < candidates.size();i++)
    	{
           
    		curSum += candidates[i];
    		if(curSum > target)
    		{
    			curSum-=candidates[i];
    			return;//剪枝
    		}
    		else if(curSum == target)
    		{
    			temp.push_back(candidates[i]);
    			ret.push_back(temp);
    			temp.pop_back();
    			curSum-=candidates[i];
    			return;//剪枝
    		}
    		else
    		{
    			temp.push_back(candidates[i]);
    			combinationSumCore(candidates,i,ret,temp,curSum,target);
    			temp.pop_back();
    			curSum-=candidates[i];
    	    }
    			
    	}

    }

    
};

posted on 2021-06-13 18:57  朴素贝叶斯  阅读(30)  评论(0编辑  收藏  举报

导航