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]
除了拼写错误,竟然一次过了……没有查有没有更优的算法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution { public : vector<vector< int > > re; vector<vector< int > > combinationSum(vector< int > &candidates, int target) { sort(candidates.begin(),candidates.end()); vector< int > tempresult; com(candidates,target,tempresult,0,-1); return re; } void com(vector< int > &candidates, int target,vector< int > now, int min, int push) { if (push>=0) { now.push_back(candidates[push]); target -= candidates[push]; } //if(candidates == NULL)return; if (target == 0) { re.push_back(now); return ; } if (target < candidates[min]) return ; for ( int i = min ; i < candidates.size(); i++) { com(candidates,target,now,i,i); } } }; |
posted on 2014-03-11 19:39 pengyu2003 阅读(110) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步