您的位置:首页 > 其它

Leetcode:Combination Sum II

2013-10-23 11:33 344 查看
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]


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


需要注意去重,这是个多重背包问题。可以统计每个数字出现的个数,此题就转化成了Combination
Sum
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: