思路:
其实就是在递归的时候避免开始递归的点和现在的点是相同的就好。也就是代码
int k=i++;
while(i<n&&candidates[i]==candidates[k])
{
i++;
}
这里实现的东西。。
public class Solution {
int [] candidates;
int n;
LinkedList<List<Integer>> result;
LinkedList<Integer>temp;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates=candidates;
n=candidates.length;
result=new LinkedList<List<Integer>>();
temp=new LinkedList<Integer>();
help(0,target);
return result;
}
void help(int start,int left)
{
int i=start;
while(i<n)
{
int currentLeft=left-candidates[i];
if(currentLeft<0)
{
return;
}
temp.add(candidates[i]);
if(currentLeft>0)
{
int k=i+1;
if(k<n)
{
help(k,currentLeft);
}
}
else// if(currentLeft==0)
{
result.add(new LinkedList<Integer>(temp));
}
temp.removeLast();
int k=i++;public class Solution {
int [] candidates;
int n;
LinkedList<List<Integer>> result;
LinkedList<Integer>temp;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates=candidates;
n=candidates.length;
result=new LinkedList<List<Integer>>();
temp=new LinkedList<Integer>();
help(0,target);
return result;
}
void help(int start,int left)
{
int i=start;
while(i<n)
{
int currentLeft=left-candidates[i];
if(currentLeft<0)
{
return;
}
temp.add(candidates[i]);
if(currentLeft>0)
{
int k=i+1;
if(k<n)
{
help(k,currentLeft);
}
}
else// if(currentLeft==0)
{
result.add(new LinkedList<Integer>(temp));
}
temp.removeLast();
int k=i++;
while(i<n&&candidates[i]==candidates[k])
{
i++;
}
}
return;
}
}
while(i<n&&candidates[i]==candidates[k])
{
i++;
}
}
return;
}
}