40. Combination Sum II

来源:互联网 发布:ambr软件 编辑:程序博客网 时间:2024/06/05 16:32

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的区别就是给的数组里的元素只能用一次

class Solution {public:    set<vector<int>> ans;    void dfs(vector<int>& candidates, int target, vector<int>& vec, int sum, int begin){        int sz = candidates.size();        for(int i = begin; i < sz; ++i){            int tmp = sum + candidates[i];            if(tmp < target){                vec.push_back(candidates[i]);                dfs(candidates, target, vec, tmp, i + 1);            } else if(tmp == target){                vec.push_back(candidates[i]);                ans.insert(vec);                vec.pop_back();                vec.pop_back();                return ;            } else if(tmp > target){                sum -= vec.back();                                vec.pop_back();                return ;            }        }        vec.pop_back();    }    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        sort(candidates.begin(), candidates.end());        vector<int> vec;        dfs(candidates, target, vec, 0, 0);        return vector<vector<int>>(ans.begin(), ans.end());    }};
原创粉丝点击