Algorithms—39.Combination Sum
2015-09-07 12:44
375 查看
思路:动态规划。
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
return f(candidates, target, new HashMap<Integer, List<List<Integer>>>());
}
public List<List<Integer>> f(int[] candidates, int target,HashMap<Integer, List<List<Integer>>> map){
if (map.get(target)==null) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
if (target<candidates[0]) {
return ans;
}
for (int i = 0; i < candidates.length; i++) {
int k=candidates[i];
if (k<target) {
List<List<Integer>> list=f(candidates,target-k,map);
if (list!=null&&list.size()!=0) {
for (int j = 0; j < list.size(); j++) {
if (list.get(j).get(0)>=k) {
List<Integer> l=new ArrayList<Integer>();
l.add(k);
l.addAll(list.get(j));
ans.add(l);
}
}
}
}else if (k==target) {
List<Integer> l=new ArrayList<Integer>();
l.add(k);
ans.add(l);
}else {
break;
}
}
map.put(target, ans);
return ans;
}
return map.get(target);
}
}
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
return f(candidates, target, new HashMap<Integer, List<List<Integer>>>());
}
public List<List<Integer>> f(int[] candidates, int target,HashMap<Integer, List<List<Integer>>> map){
if (map.get(target)==null) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
if (target<candidates[0]) {
return ans;
}
for (int i = 0; i < candidates.length; i++) {
int k=candidates[i];
if (k<target) {
List<List<Integer>> list=f(candidates,target-k,map);
if (list!=null&&list.size()!=0) {
for (int j = 0; j < list.size(); j++) {
if (list.get(j).get(0)>=k) {
List<Integer> l=new ArrayList<Integer>();
l.add(k);
l.addAll(list.get(j));
ans.add(l);
}
}
}
}else if (k==target) {
List<Integer> l=new ArrayList<Integer>();
l.add(k);
ans.add(l);
}else {
break;
}
}
map.put(target, ans);
return ans;
}
return map.get(target);
}
}
相关文章推荐
- google.com 还会换IP
- IE和Google浏览器事件传递参数不同
- Algorithm --> 棋盘中求出A到B的最小步数
- Algorithm --> 求N以内的真分数个数
- django给admin增加功能
- 悟空:用Go语言编写的全文搜索引擎
- 类别 category 以及类扩展
- 认识理解zygote
- 【哥德巴赫猜想】POJ Goldbach's Conjecture 2262
- django中给ajax提交加上csrf
- 【哥德巴赫猜想】LightOJ Goldbach`s Conjecture 1259
- Uva 11292 The Dragon of Loowater
- Intent中的四个重要属性——Action、Data、Category、Extras
- leetcode: (121) Best Time to Buy and Sell Stock
- 分类(category)
- django for windows
- hdu 1056 HangOver
- 【英语】Bingo口语笔记(69) - 脏话的表达
- POJ-2195 Going Home
- 【英语】Bingo口语笔记(68) - come系列