40. Combination Sum II

来源:互联网 发布:dsm请检查网络设置 编辑:程序博客网 时间:2024/06/05 05:21

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那道的思路非常相似,只是要注意数字不能重复使用。可以用set来避免元素的重复。

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