Combination Sum

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] 

思路:在集合中找出组合之和为目标值的集合。这让我们很容易联想到01背包问题,递归回溯累加到目标值。

class Solution {
public:
    void resolve(vector<int> &candidates,int target,int start,int sum,vector<int> &path,vector<vector<int> > &result)
    {
        if(sum>target)
            return;
        if(sum==target)
        {
            result.push_back(path);
            return;
        }
        for(int i=start;i<candidates.size();i++)
        {
            path.push_back(candidates[i]);
            resolve(candidates,target,i,sum+candidates[i],path,result);
            path.pop_back();
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > result;
        vector<int> path;
        sort(candidates.begin(),candidates.end());
        result.clear();
        path.clear();
        resolve(candidates,target,0,0,path,result);
        return result;
    }
};

 

posted @ 2014-04-25 10:35  Awy  阅读(120)  评论(0编辑  收藏  举报