[leetcode] Combination Sum II

来源:互联网 发布:炒股模拟软件 知乎 编辑:程序博客网 时间:2024/06/06 00:12
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC 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, a1a2 ≤ … ≤ 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 的基础上加上去重

代码:

class Solution {private:    vector<vector<int> > res;    vector<int> count;    map<vector<int>,int> dup;public:    vector<vector<int> > combinationSum2(vector<int> &num, int target) {        res.clear();        if(num.size()==0) return res;        sort(num.begin(),num.end());        count.clear();        count.resize(num.size());        comb(0,num.size(),target,num);        return res;    }    void comb(int index, int n, int target, vector<int> &num){        if(target<0) return;        if(index == n){            if(target == 0){                vector<int> tmp;                for(int i=0;i<n;i++){                    for(int j=0;j<count[i];j++){                        tmp.push_back(num[i]);                    }                }                if(dup.find(tmp)==dup.end()){                    res.push_back(tmp);                    dup[tmp]=1;                }                return;            }            return;        }        for(int i=0;i<=1;i++){            count[index]=i;            comb(index+1,n,target-i*num[index],num);        }    }};


 

0 0
原创粉丝点击