39. Combination Sum

来源:互联网 发布:有些源码上传会失败 编辑:程序博客网 时间:2024/06/06 20:50

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

思路:DFS
http://www.cnblogs.com/springfor/p/3884294.html
http://www.jiuzhang.com/solutions/combination-sum/

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> res;        if(candidates.size() == 0) return res;        vector<int> item;        sort(candidates.begin(), candidates.end());        helper(candidates, target, 0, item, res);        return res;    }    void helper(vector<int> candidates, int target, int start, vector<int>&item, vector<vector<int>>& res)    {        if (target < 0) return;        if (target == 0)        {            res.push_back(item);            return;        }        for (int i = start; i < candidates.size(); i++)        {            if (i > 0 && candidates[i] == candidates[i - 1]) continue;            item.push_back(candidates[i]);            int newtarget = target - candidates[i];            helper(candidates, newtarget, i, item, res);            item.erase(item.begin()+item.size()-1);        }    }};
0 0