leetcode---combination-sum-ii---dfs

来源:互联网 发布:巅峰减重 知乎 编辑:程序博客网 时间:2024/05/22 08:19

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:    void dfs(int dep, int n, vector<vector<int> > &ans, vector<int> tmp, vector<int> &num, int target)    {        if(target == 0)            ans.push_back(tmp);        for(int i=dep; i<n && target-num[i]>=0; i++)        {            if(i>dep && num[i]==num[i-1])                continue;            tmp.push_back(num[i]);            dfs(i+1, n, ans, tmp, num, target-num[i]);            tmp.pop_back();        }    }    vector<vector<int> > combinationSum2(vector<int> &num, int target)     {        sort(num.begin(), num.end());        int n = num.size();        vector<vector<int> > ans;        vector<int> tmp;        dfs(0, n, ans, tmp, num, target);        return ans;    }};