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

class Solution {
public:
    vector<vector<int> > ans;
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        /**
            [2,5,6,7] target = 7
            ouput:
            [7]
            [2,5]
            为了确保:The solution set must not contain duplicate combinations
        */
        vector<int> path;
        ans.clear();
        //sort
        sort(candidates.begin(),candidates.end());
        dfs(candidates,path,target);
        return ans;
    }
    void dfs(vector<int> & candidates, vector<int> & path,int target){
            if (target == 0){
                ans.push_back(path);
                return;
            }
            if (target < 0){
                return;
            }
            int j = 0;
            for(;j < candidates.size();j++){
                if (path.empty()){
                    break;
                }
                if (candidates[j] >= path[path.size() -1]){
                    break;
                }
            }
            for(int i = j; i < candidates.size() && target - candidates[i] >= 0; i++){
                //candidates 事先排好序
                path.resize(path.size() + 1);
                path[path.size() -1] = candidates[i];
                dfs(candidates,path,target - candidates[i]);
                path.resize(path.size() - 1);
        }
    }
};

 

posted @ 2013-06-29 09:48  一只会思考的猪  阅读(195)  评论(0编辑  收藏  举报