//如果candidates里面有重复的值,那么结果里面也会有重复的,所以要把candidates去重
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<>();
List<Integer> path=new ArrayList<Integer>();
int[] nums=removeDuplicate(candidates);
dfs(nums,0,target,path,result);
return result;
}
public void dfs(int[] candidates,int startindex,int target,List<Integer> path,List<List<Integer>> result){
if(target==0){
result.add(new ArrayList<Integer>(path));
return;
}
for(int i=startindex;i<candidates.length;i++){
if(candidates[i]>target){
break;
}
path.add(candidates[i]);
//每次从i开始就能保证不会有重复的答案。
dfs(candidates,i,target-candidates[i],path,result);
path.remove(path.size()-1);
}
}
//Remove duplicate for array(Leetcode problem)
public int[] removeDuplicate(int[] candidates){
HashSet<Integer> set=new HashSet<Integer>();
for(int i=0;i<candidates.length;i++){
set.add(candidates[i]);
}
int[] result=new int[set.size()];
//Iterator<Integer> it=set.iterator();
int index=0;
//while(it.hasNext()){
// result[index]=it.next();
//index++;
//}
for (int element : set){
result[index++] = element;
}
Arrays.sort(result);
return result;
}
class Solution {
private List<List<Integer>> result= new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates == null || candidates.length == 0) return result;
ArrayList<Integer> path = new ArrayList<Integer>();
dfs(candidates, 0, path, target);
Set<List<Integer>> set = new HashSet<>();
for(List<Integer> item: result)
{
Collections.sort(item);
set.add(item);
}
return new ArrayList<>(set);
}
public void dfs(int[] candidates, int start, ArrayList<Integer> path, int target)
{
if(target == 0)
{
result.add(new ArrayList<Integer>(path));
}
for(int i = start; i< candidates.length; i++)
{
if(candidates[i] > target)
{
continue;
}
path.add(candidates[i]);
dfs(candidates,i,path,target-candidates[i]);
path.remove(path.size()-1);
}
}
}