<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p>

<p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p>

<p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8
<strong>Output:</strong> 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> candidates = [2,5,2,1,2], target = 5
<strong>Output:</strong> 
[
[1,2,2],
[5]
]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li>
	<li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li>
	<li><code>1 &lt;= target &lt;= 30</code></li>
</ul>

class Solution {
public:
    void recurse_ans(vector<int>& candidates, map<int ,int>& um, set<map<int, int>>& s, int cur_sum, const int target, int ind, bool prev_inc) {
        if (ind >= candidates.size() || cur_sum > target) {
            return;
        }
        recurse_ans(candidates, um, s, cur_sum, target, ind + 1, false);
        /* if prev element was same and not included, do not include this! */
        if (!prev_inc && ind > 0 && candidates[ind] == candidates[ind - 1]) {
            return;
        }
        cur_sum += candidates[ind];
        if (cur_sum > target) {
            return;
        }
        um[candidates[ind]]++;
        if (cur_sum == target && s.find(um) == s.end()) {
            s.insert(um);
        }
        
        else if (cur_sum < target) {
            recurse_ans(candidates, um, s, cur_sum, target, ind + 1, true);
        }
        um[candidates[ind]]--;
    }
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        set<map<int, int>> s;
        map<int ,int> um;
        vector<vector<int>> ans;

        for (int c : candidates) {
            um[c] = 0;
        }
    
        recurse_ans(candidates, um, s, 0, target, 0, false);

        for (auto mp : s) {
            vector<int> tmp;
            for (auto p : mp) {
                for (int i = 0; i < p.second; i++) {
                    tmp.push_back(p.first);
                }
            }
            ans.push_back(tmp);
        }

        return ans;

    }
};
24044