题目:
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]
题目链接:https://leetcode.com/problems/combination-sum-ii/
分析:题意要求从给定数组找出所有组合的元素值和==target,且元素不可重复使用。该题与Combination Sum的差不多,区别在于元素不可重复使用,可以参考Combination Sum,在Combination Sum的代码基础做些细节的修改,即可。着重解决问题,去重:元素可以重复出现,需要设置判断条件去重,两种方法:
a.在target==0时,添加元素是否重复判断,调用ArrayList的contains()方法,python代码情况会出现超时,java代码可以通过测试;
b.在递归前添加去重判断,如果当前递归出现if i > begin && candidates[i] == candidates[i - 1] continue;, 因为给定数组元素出现重复,如果当前递归符合要求,紧接的递归会再次出现同样的结果,出现重复,故在当前递归直接跳过,只记录紧接的递归结果。如图所示:绿色虚线与橘色实线,在没有跳过第一次递归,直接在进行第二次递归,出现重复的组合。
Java代码Accepted:
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<Integer> subRes = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
//Special case
if(candidates.length == 0 || candidates == null)
return result;
//Sort array before find combination
Arrays.sort(candidates);
//Recursive DFS
recursionFunction(candidates,0,target,subRes,result);
return result;
}
public static void recursionFunction(int[] candidates,int begin,int target,List<Integer> subRes,List<List<Integer>> result){
if(target < 0)
return;
else if(target == 0){
//Have to redeclarat subRes as ArrayList<Integer> or can't get resSub
//Whether duplication
// if(!result.contains(new ArrayList<Integer>(subRes)))
result.add(new ArrayList<Integer>(subRes));
return;
}else{
for(int i = begin;i < candidates.length;i ++){
if(i > begin && candidates[i] == candidates[i - 1])
continue;
subRes.add(candidates[i]);
recursionFunction(candidates,i + 1,target - candidates[i],subRes,result);
subRes.remove(subRes.size() - 1);
}
}
}
}
Python Acepted:
class Solution(object):
def __init__(self):
self.res = []
self.subRes = []
self.target = 0
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
if(len(candidates) == 0 or candidates == None):
return self.res
candidates = sorted(candidates)
self.recursionFunction(candidates,0,target,self.subRes,self.res)
return self.res
def recursionFunction(self,candidates,begin,target,subRes,res):
if(target < 0):
return
elif(target == 0):
self.res.append(self.subRes)
return
else:
for i in range(begin,len(candidates)):
if i > begin and candidates[i] == candidates[i - 1]:
continue
self.subRes.append(candidates[i])
self.recursionFunction(candidates,i + 1,target - candidates[i],self.subRes,self.res)
self.subRes = self.subRes[:-1]