您的位置:首页 > 其它

Leetcode -- Combination Sum II

2015-01-28 15:06 239 查看
问题连接:https://oj.leetcode.com/problems/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 (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]

其实就是上一题加两个条件:1.每个数字只能取一次。2.解集不能有重复。

问题API:public List<List<Integer>> combinationSum2(int[] num, int target)

问题分析:

条件稍微改了,每个数字只能出现一次,所以不能local无限循环了,每次选定了当前这一个pos的元素就要往下递归一层。另外不能出现长相一样的解集,所以再每一层递归循环的时候就要判断这一个元素和之前那个是否相同,在这里,事先的排序带来了很大的便利,只需要判断当前层级的元素和上一级之前的那一个不能相等即可:

public List<List<Integer>> combinationSum2(int[] num, int target) {
int[] tmp = new int[num.length];
LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
Arrays.sort(num);
combination(num, tmp, target, 0, 0, res);
return res;
}

public void combination(int[] num, int[] tmp, int target, int curpos, int curlevel, List<List<Integer>> res){
if(target == 0){
LinkedList<Integer> curres = new LinkedList<Integer>();
for(int i = 0; i < curpos; i++){
curres.add(tmp[i]);
}
res.add(curres);
}else if(target < 0 || curlevel == num.length)
return;
else{
for(int i = curlevel; i < num.length; i++){
if(i != curlevel && num[i] == num[i - 1])
continue;
tmp[curpos] = num[i];
combination(num, tmp, target - num[i], curpos + 1, i + 1, res);
tmp[curpos] = 0;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: