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;
}
}
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;
}
}
相关文章推荐
- LSGO软件技术团队2015~2016学年第二周(0907~0912)总结
- 还记得 Google 那辆萌萌哒无人驾驶汽车吗?Google 打算把它量产
- 【原创】Django-ORM进阶
- 协议(delegate)和类别(category)
- Algorithms—18.4Sum
- some good website & books
- How Filters Work on Google Play
- STL源码剖析 [算法](二)[stl_algo.h]
- 【原创】Django-ORM基础
- Google Hacking
- Django中扩展Paginator实现分页
- HDOJ 2401 Baskets of Gold Coins (数学题)
- HDOJ 2401 Baskets of Gold Coins
- Understanding Machine Learning: From Theory to Algorithms
- Processing实现Google新图标
- HDU 4416 Good Article Good sentence
- django学习之models2
- 排序算法 golang 实现
- POJ 2000 Gold Coins
- django学习之models1