LeetCode_Combination Sum II

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很相似,只不过条件有所改动,这个题目使给定集合中可能存在相同元素,但是每个元素最多只能被使用一次。

分析:

1)同样这道题目可以使用DFS和BFS进行求解,上一题用了BFS,这里使用DFS。

2)判重方式,上一题我的判重方式直接就是在已有的解集合中进行比较判重,用在这个题目上直接就超时了;这里想了好久,比如出现如下情况:

  num集合为:[2, 1, 1, 1, 1] 最终的target:4

   所求得的结果应该是:[1,1,2]和[1,1,1,1]

  也就是说要保证出现重复的组合有被选择的机会,有不能重复选择。

class Solution{
public:
	vector <vector<int>> combinationSum2(vector <int> &num, int target){
		res.clear();
		vector <int> temp(1,0);
		sort(num.begin(),num.end());
		dfsFind(num, target, 0, temp);
		return res;
	}
private:
	vector <vector <int>> res;

	void dfsFind(vector <int> &num, 
		int target, 
		int pos, 
		vector <int> &temp){
		// If current sum greater then target  
		// then there is no need to keep try
		if(temp[0] > target){
			return ;
		}

		//Find a combination
		if(temp[0] == target){
			temp.erase(temp.begin());
			res.push_back(temp);
			temp.insert(temp.begin(),target);
			return ;
		}

		//DFS 
		for(int i=pos; i<num.size(); i++){
			//Prevent the duplicate
			if(i>pos && num[i] == num[i-1]){
			    continue;
		    }
			temp[0] += num[i];
			temp.push_back(num[i]);
			dfsFind(num, target, i+1, temp);
			temp[0] -= num[i];
			temp.pop_back();
		}
	}
};

 这里记录一下判重思路: 

 //Prevent the duplicate
			if(i>pos && num[i] == num[i-1]){
			    continue;
                        }

第一个判断条件i>pos是保证在主线上能够给出现重复数字的情况一次选择的机会:

比如:上面的例子,如果当前temp = {2,1},此时pos = 2,那么第二个1(num[2])是可以被选择的,但是在当前的搜索分支下一个num[3] = 1就不允许被选择了。

也就是说,要保证解空间搜索树中,不能存在两条完全相同的搜索路径。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值