Problem Statement

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]

Recursion Tree

For Input: candidates = [2,1,1,6], target = 8

Recursion Tree for Backtracking

Code

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        
      int n = candidates.size();
        sort(candidates.begin(),candidates.end());
      vector<vector<int>> res;
        vector<int> temp;
        func(res,candidates,temp,target,0);
        
        return res;
        
      
        
    }
    void func( vector<vector<int>>&res,vector<int>& candidates,vector<int>& temp ,int target,int start)
    {
        if(target==0)
          res.push_back(temp);
        
        else if(target<0)
          return;
        
        for(int i=start;i<candidates.size();i++)
        {
          
          if(i&&candidates[i]==candidates[i-1]&&i>start) //skip duplicates in the input
              continue;
            
          temp.push_back(candidates[i]);
        
          func(res,candidates,temp,target-candidates[i],i+1); //here i+1 is used because an element can be used atlmost once      

          temp.pop_back();
        }
    }
    
    
};