首页 > 其他 > 详细

Combination Sum I

时间:2015-09-14 12:20:51      阅读:241      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!