40. 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.

  • 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: 

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

跟上一道题Combination Sum的区别是,本道题给的数字列表内有重复的数字(如上面set有两个数字‘1’)。但是给出不重复的结果。

所以比上道题多一个避免重复的语句即可。

vector<vector<int> > combinationSum2(vector<int> &num, int target){
        vector<vector<int>> res;
        sort(num.begin(),num.end());
        vector<int> local;
        findCombination(res, 0, target, local, num);
        return res;
    }
    void findCombination(vector<vector<int>>& res, const int order, const int target, vector<int>& local, const vector<int>& num)
    {
        if(target==0){
            res.push_back(local);
            return;
        }
        else{
            for(int i = order;i<num.size();i++){ // 迭代的部分{
                if(num[i]>target) return; 
                if(i&&num[i]==num[i-1]&&i>order) continue; // 避免重复的结果 
                local.push_back(num[i]),
                findCombination(res,i+1,target-num[i],local,num); // 包含当前的数,递归
                local.pop_back();   //跳过当前的数,计算下一个数,寻找新的组合
            }
        }
    }
原文地址:https://www.cnblogs.com/hozhangel/p/7861550.html