LeetCode--Combination Sum(DFS)

来源:互联网 发布:吴青峰 知乎 编辑:程序博客网 时间:2024/05/22 03:22

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]

代码如下:

class Solution {public:    int comb(vector<int> & candidates,int sum,int target,int index,vector<vector<int> >& ans,vector<int> &tmp)    {        if(sum == target)        {            ans.push_back(tmp);            return 0;        }        if(sum > target)            return 0;        for(int i = index;i < candidates.size();i++)        {            if(i > index&&candidates[i] == candidates[i-1])             //因为同一个index的数可以被重复使用,相同值的元素则不必在使用                continue;            tmp.push_back(candidates[i]);            comb(candidates,sum+candidates[i],target,i,ans,tmp);            tmp.pop_back();        }        return 0;    }    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<vector<int> >ans;        vector<int> tmp;        tmp.clear();        ans.clear();        sort(candidates.begin(),candidates.end());        comb(candidates,0,target,0,ans,tmp);        return ans;    }};
0 0
原创粉丝点击