Combination Sum II - LeetCode
2015-11-10 14:28
344 查看
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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
A solution set is:
思路:和Combination Sum这道题基本思想是相同的。需要注意的不同点主要有两个:一个是因为每个数只能用一次,因此在枚举完后继续递归时要从下一位开始枚举,而不再是当前位置;另一个还是因为每个数只能用一次,因此要注意原数组中可能有重复数字的情况,因此这里在枚举过程中如果遇见了相同的数,则只枚举一次,然后跳过剩下的重复数字。
Each number in C may only be used once in the combination.
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
10,1,2,7,6,1,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:和Combination Sum这道题基本思想是相同的。需要注意的不同点主要有两个:一个是因为每个数只能用一次,因此在枚举完后继续递归时要从下一位开始枚举,而不再是当前位置;另一个还是因为每个数只能用一次,因此要注意原数组中可能有重复数字的情况,因此这里在枚举过程中如果遇见了相同的数,则只枚举一次,然后跳过剩下的重复数字。
class Solution { public: void assist(vector<int>& candidates, vector<vector<int> >& res, vector<int>& cur, int target, int st) { if (target == 0) { res.push_back(cur); return; } if (st == candidates.size()) return; for (int i = st, n = candidates.size(); i < n && candidates[i] <= target; i++) { cur.push_back(candidates[i]); assist(candidates, res, cur, target - candidates[i], i + 1); cur.pop_back(); while (i < n && candidates[i] == candidates[i + 1]) i++; } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int> > res; vector<int> cur; sort(candidates.begin(), candidates.end(), less<int>()); assist(candidates, res, cur, target, 0); return res; } };
相关文章推荐
- LNMP 常见502问题汇总
- 记录部件中GetItemControlByFieldName(字段标签样式设置)用法
- 11 个超实用的网站页脚设计小技巧—兄弟连IT教育
- postgresql常用命令
- pb连接oracle问题
- Restful架构思想理解
- 【Java并发编程】:并发新特性—障碍器CyclicBarrier(含代码)
- linux时区问题
- HTTP 状态码整理
- C# winform窗体在桌面右下角显示(任务栏上方)
- GDB高级用法
- 模拟业务最小测试用例01
- F12调试界面植入招聘信息
- js 判断字符是否以汉字开头
- 解压.tar.gz出错gzip: stdin: not in gzip format tar: /Child returned status 1 tar: Error is not recoverable: exiting now
- web -- JS代码库
- shell-bash学习01基础、打印、环境变量
- 说说
- C++中将数据保存成jpg格式图片
- 在JSTL EL中处理java.util.Map,及嵌套List集合