40. Combination Sum II

来源:互联网 发布:马哲外设淘宝店 编辑:程序博客网 时间:2024/06/03 18:53

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]]

思路大体同Combination Sum,不过是要注意一些特殊情况(重复元素)的处理。

解题代码

class Solution {private:    vector<vector<int>> res;    void generateCombinations(vector<int>& candidates, int start, int target, vector<int> &c){        // 递归终止,找到组合的情况        if (target == 0){            res.push_back(c);            return;        }        // 递归过程        for (int i = start; i < candidates.size(); i++){            // 考察当前元素有没有可能放到答案中,当前考察元素已经超过target直接考察下一个元素            if (target < candidates[i]) continue;            if (start != i&&candidates[i] == candidates[i - 1]) continue;//重复的组合只考虑一个            c.push_back(candidates[i]);            // 递归过程:因为不可重复取值,因此还是尝试从i+1开始继续寻找            generateCombinations(candidates, i+1, target - candidates[i], c);            c.pop_back(); // 递归回溯,为下一次递归推入做准备        }        return;    }public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        sort(candidates.begin(), candidates.end());        //Utils::showVecInfo(candidates);        res.clear();        // 边界条件        if (candidates.empty()) return res;        vector<int> c;        generateCombinations(candidates, 0, target, c);        return res;    }};

测试

class TestHelper{    Solution s;public:    void run(){        int candiate[] = { 10, 1, 2, 7, 6, 1, 5 }, target = 8;        vector<int> vec(candiate, candiate + 7);        Utils::showVecInfo(vec);        vector<vector<int>> res = s.combinationSum(vec, target);        // 显示结果信息        Utils::showVecInfo(res);    }};

工具类同Combination Sum。

结果

vector : [ 10 1 2 7 6 1 5 ]vector<vector<int>> :                        [                          [ 1 1 6 ]                          [ 1 2 5 ]                          [ 1 7 ]                          [ 2 6 ]                        ]请按任意键继续. . .
原创粉丝点击