Leetcode: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:
    vector > combinationSum2(vector &num, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector > v_results;
        if(num.empty() )
            return v_results;   
        sort(num.begin(),num.end() );
        vector result;
        helper(num,0,target,result,v_results);
        return v_results;
    }
    void helper(vector& candidates,int pos,int target,vector& result,vector >& v_results)
    {   
        if(target==0)
        {   
            v_results.push_back(result);
            return;
        }   
        if(target<0 || pos>=candidates.size() )
            return;
        //qu
        result.push_back(candidates[pos]);
        helper(candidates,pos+1,target-candidates[pos],result,v_results);
        result.pop_back();
        //not qu
        int tmp=pos;
        while(tmp

需要注意去重,这是个多重背包问题。可以统计每个数字出现的个数, 此题就转化成了 Combination Sum

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