首页 > 代码库 > [LeetCode: 题解] Combination Sum

[LeetCode: 题解] 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, a1a2 ≤ … ≤ 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]

题意:

给定一个候选集合,集合中的元素以非递减方式存放。给定一个目标值T

输出所有唯一的组合。

思路:

由于不能出现重复元组,所以我们先将candidate set进行排序,然后规定比新插入的元素不能比当前元素小。

采用DFS思想即可。

解法如下:

 

class Solution {private:    vector<int> ans;    vector<vector<int> > ret;public:    void DFS(int start,vector<int> &candidates, int target){        if(target==0){            ret.push_back(ans);            return;        }        for(int i=start;i<candidates.size();++i){            if(target <candidates[i]) return;            ans.push_back(candidates[i]);            DFS(i,candidates,target-candidates[i]);            ans.pop_back();        }    }    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        ans.clear();        ret.clear();        if(!target || !candidates.size()) return ret;        sort(candidates.begin(),candidates.end());        DFS(0,candidates,target);        return ret;    }};

 

-------------------------------------------------

作者:Double_Win

出处: http://www.cnblogs.com/double-win/p/3896010.html 

声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~