首页 > 代码库 > [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, 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]
题意:
给定一个候选集合,集合中的元素以非递减方式存放。给定一个目标值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 声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~ |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。