Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
与39题类似 但会出现重复的结果值 最通俗的方法如下:
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
getRes(res, new ArrayList<>(), target, 0, 0, candidates);
return res;
}
public void getRes(List<List<Integer>> res, List<Integer> tmpValue, int target, int now, int beginIndex,
int[] candidates) {
if (!tmpValue.isEmpty() && now == target) {
List<Integer> tmpRes = new ArrayList<>(tmpValue);
Collections.sort(tmpRes);
if(!res.contains(tmpRes)) {
res.add(tmpRes);
}
}
for (int index = beginIndex; index < candidates.length; index++) {
now += candidates[index];
int tmpIndex = index;
tmpValue.add(candidates[index]);
if(now <= target) {
getRes(res,tmpValue,target,now,++tmpIndex,candidates);
}
now -= candidates[index];
if (tmpValue != null && tmpValue.size() >= 1) {
tmpValue.remove(tmpValue.size() - 1);
}
}
}
对于数据去重的优化 可以先对数组进行排序 ,然后只对重复数据的第一个进行获取结果 改进后代码如下:
// 不可重复使用 但有重复数据
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
getRes(res, new ArrayList<>(), target, 0, 0, candidates);
return res;
}
public void getRes(List<List<Integer>> res, List<Integer> tmpValue, int target, int now, int beginIndex,
int[] candidates) {
if (!tmpValue.isEmpty() && now == target) {
res.add(new ArrayList<>(tmpValue));
}
for (int index = beginIndex; index < candidates.length; index++) {
now += candidates[index];
int tmpIndex = index;
tmpValue.add(candidates[index]);
if(now <= target) {
getRes(res,tmpValue,target,now,++tmpIndex,candidates);
}
now -= candidates[index];
if (tmpValue != null && tmpValue.size() >= 1) {
tmpValue.remove(tmpValue.size() - 1);
}
while(index+1 < candidates.length && candidates[index]==candidates[index+1]) index++;
}
}