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

Combination Sum

时间:2014-11-27 10:27:04      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   使用   

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 (a1, a2, … , 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] 

使用递归的方法实现:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        if(candidates.empty())
            return vector<vector<int> >();
        sort(candidates.begin(),candidates.end());
        vector<vector<int> > ret;
        vector<int> path;
        combination(candidates,0,target,ret,path);
        return ret;
    }

    void combination(vector<int> &candidates,int start,int target,vector<vector<int> > &ret,vector<int> &path)
    {
        if(target<0)
            return;
        if(target==0)
        {
            ret.push_back(path);
            return;
        }
        int i;
        for(i=start;i<(int)candidates.size();i++)
        {
            path.push_back(candidates[i]);
            combination(candidates,i,target-candidates[i],ret,path);
            path.pop_back();
        }
    }
};

int main()
{
    Solution s;
    vector<int> vec={2,3,6,7};
    vector<vector<int> > result=s.combinationSum(vec,7);
    for(auto a:result)
    {
        for(auto v:a)
            cout<<v<<" ";
        cout<<endl;
    }
}

运行结果:

bubuko.com,布布扣

Combination Sum

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://www.cnblogs.com/wuchanming/p/4125608.html

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