LeetCode 39. Combination Sum
来源:互联网 发布:arm ds5 linux 破解版 编辑:程序博客网 时间:2024/05/22 03:07
Given a set of candidate numbers (C) and a target number (T), find all unique combinations inC 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.
2,3,6,7
and target 7
, A solution set is:
[7]
[2, 2, 3]
Need to pay special attention to the condition that "The number can be used repeatedly", we thus use a pointer to pointer to the value used and not adding one when being used in the next level.
#include <vector>#include <iostream>#include <algorithm>using namespace std;void combinationSum(vector<int>& candidates, int start, vector< vector<int> >& res, vector<int>& path, int& sum, int target) { if(sum > target) return; if(sum == target) { res.push_back(path); } for(int i = start; i < candidates.size(); ++i) { sum += candidates[i]; path.push_back(candidates[i]); combinationSum(candidates, i, res, path, sum, target); path.pop_back(); sum -= candidates[i]; }}vector< vector<int> > combinationSum(vector<int>& candidates, int target) { vector< vector<int> > res; vector<int> path; sort(candidates.begin(), candidates.end()); int sum = 0; combinationSum(candidates, 0, res, path, sum, target); return res;}int main(void) { vector<int> candidates{2, 3, 6, 7}; vector< vector<int> > res = combinationSum(candidates, 7); for(int i = 0; i < res.size(); ++i) { for(int j = 0; j < res[0].size(); ++j) { cout << res[i][j] << endl; } cout << endl; }}
0 0
- [LeetCode]39.Combination Sum
- LeetCode --- 39. Combination Sum
- LeetCode 39.Combination Sum
- [Leetcode] 39. Combination Sum
- Leetcode-39.Combination Sum
- LeetCode 39. Combination Sum
- [LeetCode]39. Combination Sum
- 39. Combination Sum LeetCode
- [leetcode] 39. Combination Sum
- leetcode 39. Combination Sum
- 【leetcode】 39. Combination Sum
- LeetCode 39. Combination Sum
- leetcode 39. Combination Sum
- LeetCode 39. Combination Sum
- LeetCode *** 39. Combination Sum
- LeetCode 39. Combination Sum
- leetcode 39. Combination Sum
- LeetCode - 39. Combination Sum
- 移动端web开发技巧
- C/C++系列之学生管理系统
- windows内核编程之手动提升进程权限
- 移动HTML5前端性能优化指南
- MyBatis学习记录(1):牛刀小试,入门程序
- LeetCode 39. Combination Sum
- win7环境(x64)安装MySQL 5.7.12出现3534错误解决备忘
- Android MediaRecorder系统结构
- 生活感悟
- Android类动态加载技术
- HTML学习笔记(四)——分组元素
- 为何要学习unreal engine4
- imageview 不显示的问题
- CSS3盒模型-box-shadow详细解析