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 (a1, a2, … , 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] 

思路:这道题的思路和Combination Sum差不多,01背包的思想,但是此题有重复元素出现,可想而知,也会有重复的数组出现。故在上题的基础上,修改了一下,如果出现了相同的元素,则我们使用后面一个元素。记得一定要先排序,然后在处理数据。

class Solution {
public:
    void resolve(vector<int> &num,int target,int start,int sum,vector<int> &path,vector<vector<int> > &result)
    {
        if(sum>target)
            return;
        if(sum==target)
        {
            result.push_back(path);
            return;
        }
        for(int i=start;i<num.size();i++)
        {
            path.push_back(num[i]);
            resolve(num,target,i+1,sum+num[i],path,result);
            path.pop_back();
            while(i<num.size()-1 && num[i]==num[i+1])
                i++;
        }
    }
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        vector<vector<int> > result;
        vector<int> path;
        result.clear();
        path.clear();
        sort(num.begin(),num.end());
        resolve(num,target,0,0,path,result);
        return result;
    }
};
原文地址:https://www.cnblogs.com/awy-blog/p/3688227.html