题目一:组合总和
思路:首先定义一个全局变量list用于存储最终所有组合,对数组进行升序排序,如果元素相同,则第一次之后出现的重复元素不再作为第一个元素进行操作,以达到去重的效果,接着定义函数backtarget用于每组符合条件的元素。backtarget函数,参数一用于记录每一组数据中的每一个元素,参数二表示该组合之和,参数三表示从index开始选一个元素,参数四目标值,参数五待操作数组。如果sum>target,则不符合,返回,如果等于,则符合,将其加入list集合中,如果没有选择完毕,则利用一个循环让每一个元素都能作为第一个数,如果有重复元素,则跳出本次循环,以达到去重效果,然后将选出的该元素加入temp集合中,接着选下一个元素,直到大于等于target,然后再将temp集合中的所有元素去除,选择下一个元素作为第一个数据,直到所有元素都选中过。
代码:
private static List<List<Integer>> list;
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
list=new ArrayList<List<Integer>>();
Arrays.sort(candidates);
List<Integer> temp=new ArrayList<Integer>();
backtarget(temp, 0, 0, target, candidates);
return list;
}
public static void backtarget(List<Integer> temp,int sum,int index,int target,int[] candidates) {
if(sum>target) {
return;
}
if(sum==target) {
list.add(new ArrayList<Integer>(temp));
return;
}
for(int i=index;i<candidates.length;i++) {
if(i>index&&candidates[i]==candidates[i-1]) {
continue;
}
temp.add(candidates[i]);
backtarget(temp, sum+candidates[i], i+1, target, candidates);
temp.remove(temp.size()-1);
}
}
运行成功截图: