LeetCode——040
2016-04-17 10:32
330 查看
/*
40. Combination Sum II My Submissions QuestionEditorial Solution
Total Accepted: 66386 Total Submissions: 241547 Difficulty: Medium
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Subscribe to see which companies asked this question
*/
/*
解题思路:
此题与上一题很相似,只是要求每个元素只能用依次。当我们遍历到某个元素时有两种选择添加或者不添加。结果判断条件:target==0 (还要判断是否已经遍历到数组末尾)
同样,在本题中也是用了set来防止有重复的结果
*/
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { //本题与上一题非常相似,只是要求每个元素只能使用一次 if(candidates.empty())return {}; set<vector<int>> _set; vector<int> out; sort(candidates.begin(),candidates.end()); dfs(candidates,0,target,out,_set); return vector<vector<int>> (_set.begin(),_set.end()); } void dfs(vector<int> &candidates,int start,int target,vector<int>&out,set<vector<int>>&_set){ if(target<0)return ; if(target==0){ _set.insert(out); return ; } if(start==candidates.size())return ; dfs(candidates,start+1,target,out,_set); out.push_back(candidates[start]); dfs(candidates,start+1,target-out.back(),out,_set); out.pop_back(); } };
相关文章推荐
- Grbl-51
- Mybatis 动态sql 小结
- JSON之Jackson(二)
- CSP考试 2015年12月第1题 数位之和 C语言实现
- SPOJ15710 Iterated sums
- C++封装、继承、多态
- 第七周学习进度
- linux第四次读书笔记
- LightOJ 1341 Aladdin and the Flying Carpet【整数分解】
- Kali 强大的抓包工具 WIRESHARK
- LightOJ 1341 Aladdin and the Flying Carpet【整数分解】
- LightOJ 1341 Aladdin and the Flying Carpet【整数分解】
- 视频封装格式之mkv--1
- java native关键字
- 20145236 《Java程序设计》实验二实验报告
- 进程间的通信方式与进程间同步方式
- php session和cookie
- IE请求和响应报文解释
- BestCoder Round #80(B)高精度
- 一些linux的基本操作