【LeetCode】107.Combination Sum II

题目描述(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) will be positive integers.
  • 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();
        }
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/83302418
今日推荐