您的位置:首页 > 其它

Combination Sum II

2016-05-11 08:47 309 查看
题目:

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]


题意:给定一个数组C和一个特定值T,要求找出这里面满足以下条件的所有答案:数组中数字的值加起来等于特定和的答案.[b]并且数组中的数字不允许被使用多次,但如果一开始就存在多个的话,可以使用多次。[/b]

[b]分析:[/b]

[b] 可以采用与Combination Sum 类似的方法,但是由于题二中的每个数只能取一次,所以dfs函数中的for循环,i应从l+1开始,表示取下一个数。但这样带来的问题是,结果中会出现重复的取数方案,拿上面的例子来分析:C中有两个1可以选,那第一个1和7是一种可选方案(1+7=8),第二个1和7也是一种可选方案,按照上述算法,[1,7]会在结果中出现两次。当然可以对最后结果去重(如果用C++的话,sort->unique->erase可以实现)。不幸的是,这种解法会超时。解决超时的方案是不要将重复的方案加入到结果集中,也就避免了去重的工作。[/b]


<pre name="code" class="java">public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target) {
LinkedList<List<Integer>> res=new LinkedList<List<Integer>>();
LinkedList<Integer> list=new LinkedList<Integer>();
if(num==null || num.length<=0) return res;
Arrays.sort(num);
dfs(0,0,target,num,list,res);
HashSet set=new HashSet(res);
res.clear();
res.addAll(set);
return res;
}
public void dfs(int start,int sum,int target,int[] num,LinkedList<Integer> list,List<List<Integer>> res){
if(sum==target){
LinkedList<Integer> l=new LinkedList<Integer>(list);
res.add(l);
return;
}
for(int i=start;i<num.length;i++){
if(sum+num[i]>target) return;
list.add(num[i]);
dfs(i+1,sum+num[i],target,num,list,res);
list.pollLast();
}
}
}







注意:用set剔除重复的组。

[b]c++:[/b]


class Solution {
public:
void internalCombinationSum2(vector<int> &num,
int start,
int sum,
int target,
vector<int> &combination,
vector<vector<int> > &result) {
int size = num.size();

if (sum == target) {
result.push_back(combination);

return;
}
else if ((start >= size) || (sum > target)) {
return;
}

for (int i = start; i < size; ) {
combination.push_back(num[i]);
internalCombinationSum2(num, i + 1, sum + num[i], target, combination, result);
combination.pop_back();

int j = i + 1;

while (j < size) {
if (num[i] == num[j]) {
++j;
}
else {
break;
}
}

i = j;
}
}

vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > result;
vector<int> combination;

sort(num.begin(), num.end());
internalCombinationSum2(num, 0, 0, target, combination, result);

return result;
}
};

http://www.cnblogs.com/panda_lin/archive/2013/11/05/combination_sum_ii.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: