LeetCode_Combination Sum II

来源:互联网 发布:怎么成为阿里云代理商 编辑:程序博客网 时间:2024/05/24 16:15

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC where the candidate numbers sums toT.

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 tryif(temp[0] > target){return ;}//Find a combinationif(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 duplicateif(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 duplicateif(i>pos && num[i] == num[i-1]){    continue;                        }

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

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

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

0 0
原创粉丝点击