40. Combination Sum II

来源:互联网 发布:mac 多屏幕切换快捷键 编辑:程序博客网 时间:2024/06/04 19:09

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

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> tmp;
        sort(candidates.begin(),candidates.end());
        dfs(res,tmp,candidates,target,0);
        return res;
        
    }
    void dfs(vector<vector<int>> &res,vector<int> &tmp,vector<int> &candidates,int target,int pos)
    {
        if(target<0) return ;
        if(target==0)  
        {
         res.push_back(tmp);
         return ;
        }
        for(int i=pos;i<candidates.size();i++)
        {
           tmp.push_back(candidates[i]);
           dfs(res,tmp,candidates,target-candidates[i],i+1);
           tmp.pop_back();
           while(i<candidates.size()-1&&candidates[i+1]==candidates[i]) i++;
        }
        
    }
};:

0 0