码迷,mamicode.com
首页 > 其他好文 > 详细

Combination Sum I

时间:2015-09-14 12:23:55      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:including   positive   repeated   solution   contain   

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 (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).

  • 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] 

解法:

由题意为set知,集合应该没有重复元素;用回溯法。

注意,每个元素可以取多次,

void  combinationCore(vector<int> &candi,int target,int begin,vector<int> &tempresult,vector<vector<int> > &results){

        if(target==0){//target==0,说明已经找到一个可行解

            results.push_back(tempresult);

        }

        else{

            int size=candi.size();

            for(int i=begin;i<size&&target>=candi[i];++i){

         //target>=candi[i],因为同一个元素可以取多次,则i从begin开始,且下一个也是从i开始,

                tempresult.push_back(candi[i]);

                combinationCore(candi,target-candi[i],i,tempresult,results);

                tempresult.pop_back();

            }

        }

    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {

        

        vector<vector<int>> results;

        int size=candidates.size();

        if(size==0||target<=0)

            return results;

        vector<int> temp;

        sort(candidates.begin(),candidates.end());//must

        combinationCore(candidates,target,0,temp,results);

        return results;

    }


Combination Sum I

标签:including   positive   repeated   solution   contain   

原文地址:http://searchcoding.blog.51cto.com/1335412/1694490

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!