Combination Sum II

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 (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

class Solution {
public:
    void visit(vector<int> &candidates, map<int, int> &counter, int n, int pos, 
               int target, int sum,  vector<vector<int> > &result, vector<int> &buf)
    {
	    if (sum == target)
	    {
		    result.push_back(buf);
		    return;
	    }
	    if (pos >= n)
	    {
		    return;
	    }

	    int maxNum = counter[candidates[pos]];
	    for (int i = 0; i <= maxNum; i++)
	    {
		    int temp = sum + candidates[pos]*i;
		    if (temp > target)
		    {
			    break;
		    }
		    else
		    {
			    for (int j = 0; j < i; j++)
			    {
				    buf.push_back(candidates[pos]);
			    }
			    visit(candidates, counter, n, pos+maxNum, target, temp, result, buf);
			    for (int j = 0; j < i; j++)
			    {
				    buf.pop_back();
			    }
		    }
	    }
    }
    
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        int n = candidates.size();
	    vector<vector<int> > result;
	    if (n < 1)
	    {
	        return result;
	    }
	    
	    sort(candidates.begin(), candidates.end());
	    vector<int> buf;
	    map<int, int> counter;
	    int sum = 0; 
	    int val = candidates[0];
	    int num = 1;
	    for (int i = 1; i < n; i++)
	    {
	        if (candidates[i] == val)
	        {
	            num++;
	        }
	        else
	        {
	            counter[val] = num;
	            val = candidates[i];
	            num = 1;
	        }
	    }
	    counter[val] = num;
	    visit(candidates, counter, n, 0, target, sum, result, buf);

	    return result;
    }
};


你可能感兴趣的:(Combination Sum II)