题目内容
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:
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]
]
分析过程
- 题目归类:
使用后删除类题目
- 题目分析:
递归处理使用后删除即可。掌握方法就很简单
- 边界分析:
- 方法分析:
- 测试用例构建
代码实现
import java.util.*;
class Solution {
List<List<Integer>> list = new ArrayList<>();
List<Integer> arraylist = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
return Sum(candidates, target,0);
}
public List<List<Integer>> Sum(int[] candidates, int target,int s){
if(target==0){
if(!list.contains(arraylist))
list.add(new ArrayList(arraylist));
return list;
}
for(int i = s; i< candidates.length;i++ ) {
if(candidates[i]>target){
break;
}
arraylist.add(candidates[i]);
Sum(candidates,target-candidates[i],i+1);
arraylist.remove(arraylist.size()-1);
}
return list;
}
}
效率提高
拓展问题