combination-sum-ii

来源:互联网 发布:数据修约标准 编辑:程序博客网 时间:2024/06/06 10: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.
Elements in a combination (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
The solution set must not contain duplicate combinations.

For example, given candidate set10,1,2,7,6,1,5and target8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

程序:

class Solution {public:    vector<vector<int> > combinationSum2(vector<int> &num, int target) {        set<vector<int>> s;        sum(num, target, s,0);        vector<vector<int>> res(s.begin(), s.end());        return res;    }    void sum(vector<int> &candidates, int target, set<vector<int>> &res,int beg)    {        vector<int> temp;        if (target == 0)        {            temp = v;            sort(temp.begin(), temp.end());            res.insert(temp);            return;        }        else if (target < 0)            return;        for (int i = beg; i < candidates.size(); i++)        {            v.push_back(candidates[i]);             sum(candidates, target - candidates[i], res,i+1);            v.pop_back();        }    }    vector<int> v;};

点评:

递归