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]
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public : void findSum(vector< int > &S, int sum, int level, int &t,vector< int > &buf,vector<vector< int >> &res){ for ( int i=level;i<S.size();i++){ buf.push_back(S[i]); if (sum+S[i]==t) res.push_back(buf); if (sum+S[i]<=t) findSum(S,sum+S[i],i,t,buf,res); buf.pop_back(); } } vector<vector< int > > combinationSum(vector< int > &candidates, int target) { vector< int > buf; vector<vector< int >> res; sort(candidates.begin(),candidates.end()); findSum(candidates,0,0,target,buf,res); return res; } }; |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步