您的位置:首页 > 编程语言 > Go语言

Algorithms—40.Combination Sum II

2015-09-14 11:41 495 查看
思路:先排序,然后逆向取数,如果这个数小于目标值,则将该数于目标的差值带入,递归查询。

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
return f(candidates,target,candidates.length-1);
}
public List<List<Integer>> f(int[] candidates, int target,int l) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
if (candidates[0]>target||target<0||l<0) {
return ans;
}
for (int i =l; i >=0 ; i--) {
int k=candidates[i];
if (k==target) {
List<Integer> list=new ArrayList<Integer>();
list.add(k);
ans.add(list);
}else {
List<List<Integer>> q=f(candidates,target-k,i-1);
if (q!=null&&q.size()!=0) {
for (int j = 0; j < q.size(); j++) {
List<Integer> list=q.get(j);
list.add(k);
ans.add(list);
}
}
}
while (i>0&&candidates[i]==candidates[i-1]) {
i--;
}
}
return ans;
}
}

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