[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]
一开始想到用背包DP做,用DP的好处是速度快。但打印结果比较麻烦。DP比较适合打印总共有几种情况。所以就用DFS来做。
1 class Solution { 2 private: 3 vector<vector<int> > ret; 4 vector<int> a; 5 public: 6 void solve(int dep, int maxDep, int target, vector<int> &cand) 7 { 8 if (target < 0) 9 return; 10 11 if (dep == maxDep) 12 { 13 if (target == 0) 14 { 15 vector<int> res; 16 for(int i = 0; i < maxDep; i++) 17 for(int j = 0; j < a[i]; j++) 18 res.push_back(cand[i]); 19 ret.push_back(res); 20 } 21 return; 22 } 23 24 for(int i = 0; i <= target / cand[dep]; i++) 25 { 26 a[dep] = i; 27 solve(dep + 1, maxDep, target - cand[dep] * i, cand); 28 } 29 } 30 31 vector<vector<int> > combinationSum(vector<int> &candidates, int target) { 32 // Start typing your C/C++ solution below 33 // DO NOT write int main() function 34 sort(candidates.begin(), candidates.end()); 35 36 a.resize(candidates.size()); 37 ret.clear(); 38 if (candidates.size() == 0) 39 return ret; 40 41 solve(0, candidates.size(), target, candidates); 42 43 return ret; 44 } 45 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】