[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] 

有点像01背包,  稍微改动了一下,先预处理去重,统计每个元素的数, 深度遍历的时候 约束条件添加 不能超过Num[i]


class Solution {
private:
    vector<vector <int> > ret;
    vector <int> count;
    vector <int> num;
public:
	void help(int current_index, int max_index, int target , vector<int> & candidates){

		if(target <0)
			return ;
        if(current_index == max_index)
		{
	    	if(target == 0)
			{
		        vector<int> tmp;
		    	for(int i = 0 ; i <  max_index; i++)
			    	for(int j = 0 ; j < count[i]; j++)
				    	tmp.push_back(candidates[i]);
		    	
		    	ret.push_back(tmp);
		    	return ;
	    	}
            return ;
         }
		for(int i = 0; i <= num[current_index] && i <= target/candidates[current_index]; i++)
		{
			count[current_index] = i;
			help(current_index+1,max_index, target - i*candidates[current_index],candidates);
		}
	}
    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
     ret.clear();
	 vector <int> can;
	 int pre = 0;
    if(candidates.size()==0)
        return ret;
    sort (candidates.begin(),candidates.end()); 

    num.clear();
    num.resize(candidates.size());
    int j = -1;
	for(int i = 0 ; i < candidates.size(); i++)
	{
		if(candidates[i]==pre)
		{
			num[j]++;
		}else{
			j++;
			can.push_back(candidates[i]);
            pre =candidates[i];
			num[j] = 1;
		}
	}
    count.clear();
    count.resize(candidates.size());
	help(0,can.size(), target,can);
	return  ret;
    }
};

posted @ 2012-11-08 16:52  程序员杰诺斯  阅读(101)  评论(0)    收藏  举报