标签:leetcode 面试 combination sum
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:
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]
此题目,candidates有重复的数字出现。
在leetcode上实际执行时间为23ms。
class Solution { public: vector<vector<int> > combinationSum2(vector<int> &candidates, int target) { vector<vector<int> > result; sort(candidates.begin(), candidates.end()); vector<int> solution; helper(result, solution, candidates, 0, target); return result; } void helper(vector<vector<int> >&result, vector<int> &solution, const vector<int> &candidates, int index, int target) { if (!target) result.push_back(solution); else if (target < 0) return; for (int i = index; i < candidates.size(); i++) { solution.push_back(candidates[i]); helper(result, solution, candidates, i+1, target-candidates[i]); solution.pop_back(); while (i+1 < candidates.size() && candidates[i] == candidates[i+1]) i++; } } };
Combination Sum II -- leetcode
标签:leetcode 面试 combination sum
原文地址:http://blog.csdn.net/elton_xiao/article/details/42777907