LeetCode40 Combination Sum II 累加相同组合 II

题目描述:
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.
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]
]
题源:here;完整实现:here
思路:
同上一题,不同的是,这一次输入中包含有重复数,并且需要每个数只用一次,所以添加了一个用于记录当前添加数的指针,并要去除重复的情况,代码如下:

class Solution {
public:
    vector<vector<int>> result;
    void recurse(vector<int> candidates, int target, vector<int> curr, int currIdx){
        int sum = accumulate(curr.begin(), curr.end(), 0);
        if (sum == target){
            result.push_back(curr); return;
        }
        else if (sum > target) return;

        for (int i = currIdx+1; i < candidates.size(); i++){
            if (i > currIdx + 1 && candidates[i] == candidates[i - 1]) continue;
            curr.push_back(candidates[i]);
            recurse(candidates, target, curr, i);
            curr.pop_back();
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<int> curr;
        sort(candidates.begin(), candidates.end());

        recurse(candidates, target, curr, -1);
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80795060