Leetcode: 40. Combination Sum II(Week13, Medium)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linwh8/article/details/78769203

Leetcode 40
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.
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]
]

  • 题意:给出一个数字序列和目标值,要求从数字序列中得到所有组合(组合不能重复),且序列中每个数字只能使用一次,最终使得每个组合的和等于目标值
  • 思路:与Leetcode39 的Combination Sum思路差不多,只不过要做点修改:在主函数中循环调用递归函数,将递归函数中for循环的循环变量初始化+1,以避免重复使用数字序列中的数字。但是由于示例中的数字序列是有重复数字的,这样会导致最终的组合中可能会有重复答案,所以使用了set来进行去重操作。
  • 代码如下:
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        //candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());
        set<vector<int>> s;
        vector<vector<int>> result;
        vector<int> temp_result;
        for (int i = 0; i < candidates.size(); i++) {
            temp_result.push_back(candidates[i]);
            solve_Combination_Sum(candidates, s, temp_result, target-candidates[i], i);
            temp_result.pop_back();
        }
        for (auto it = s.begin(); it != s.end(); it++) {
            result.push_back(*it);
        }
        return result;
    }
    void solve_Combination_Sum(vector<int>& candidates, set<vector<int>>& result, vector<int>& out, int target, int index) {
        if (target < 0) return;
        if (target == 0) {
            result.insert(out);
        }
        for (int i = index+1; i < candidates.size(); i++) {
            out.push_back(candidates[i]);
            solve_Combination_Sum(candidates, result, out, target-candidates[i], i);
            out.pop_back();
        }
    }   
};

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


猜你喜欢

转载自blog.csdn.net/linwh8/article/details/78769203