一、问题描述
这个题目有点类似于 LeetCode-39.,但是有几点不同:
- 数组candidates中可以包含重复元素
- 解组合中数组中的元素不能重复出现,一个解组合中,一个元素出现的次数必须小于等于数组中钙元素出现的次数
二、
三、代码
public class Solution { List<List<Integer>> result=new ArrayList<List<Integer>>(); public List<List<Integer>> combinationSum2(int[] candidates, int target) { if(candidates==null || candidates.length==0) return result; Arrays.sort(candidates); for(int i=0;i<candidates.length;i++){ if(i!=0 && candidates[i]==candidates[i-1])//i不等于0时,会判断当前元素与前一个元素是否相同 continue; core(candidates,0,i,target,new ArrayList<Integer>()); } return result; } private int core(int[] candidates,int count,int point,int target,List<Integer> tem){ count+=candidates[point]; if(count==target){ tem.add(candidates[point]); result.add(new ArrayList<Integer>(tem)); tem.remove((Object)candidates[point]); return 0; }else if(count<target){ tem.add(candidates[point]); for(int i=point+1;i<candidates.length;i++){//i从point+1开始,不再是point if(i!=point+1 && candidates[i]==candidates[i-1])//如果i不等于point+1,判断当前元素与前一个元素是否相同。起始判定的元//素只能是point+1,而不能是0,至于为什么,可以自己考虑 continue; if(core(candidates,count,i,target,tem)>=0) break; } tem.remove((Object)candidates[point]); return -1; }else{ return 1; } } }