【LeetCode】107.Combination Sum II
阿新 • • 發佈:2018-11-01
題目描述(Medium)
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
- The solution set must not contain duplicate combinations.
題目連結
https://leetcode.com/problems/combination-sum-ii/description/
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
演算法分析
參考【LeetCode】106.Combination Sum,本題需要考慮重複數字,先對原始陣列排序,並用一個變數記錄上一個使用的數值,重複即跳過。
提交程式碼:
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<int> solution; sort(candidates.begin(), candidates.end()); dfs(candidates, solution, target, 0, 0);int previous = -1; return this->result; } private: vector<vector<int>> result; void dfs(vector<int>& candidates, vector<int>& solution, int target, int cur_sum, int start) { if (cur_sum == target && start <= candidates.size()) { this->result.push_back(solution); return; } int previous = -1; for (int i = start; i < candidates.size(); ++i) { cur_sum += candidates[i]; solution.push_back(candidates[i]); if (cur_sum <= target && previous != candidates[i]) { dfs(candidates, solution, target, cur_sum, i + 1); previous = candidates[i]; } cur_sum -= candidates[i]; solution.pop_back(); } } };