combination sum

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class  {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list=new ArrayList<>();
Arrays.sort(candidates);
backTrack(list,new ArrayList<>(),candidates,target,0);
return list;
}
public void backTrack(List<List<Integer>> list,ArrayList<Integer> tempList,int [] nums,int remain,int start)
{
if(remain<0)
return;
else if(remain==0)
{
list.add(new ArrayList<>(tempList));
}
else
{
for(int i=start;i<nums.length;i++)
{
tempList.add(nums[i]);
backTrack(list,tempList,nums,remain-nums[i],i);
tempList.remove(tempList.size()-1);
}
}
}
}

TIPS:
递归