您的位置:首页 > 其它

leetcode Combination Sum II

2015-10-23 19:08 399 查看
题目链接

思路:

其实就是在递归的时候避免开始递归的点和现在的点是相同的就好。也就是代码

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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: