您的位置:首页 > 其它

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();

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: