标签:
先贴代码,容后补内容
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); solve(candidates,0,target,new LinkedList<Integer>()); return ans; } private List<List<Integer>> ans=new LinkedList<>(); private void solve(int[] candidates,int start,int target,LinkedList<Integer> current){ if (target==0){ ans.add(copy(current)); return; } if (target<candidates[start]){ return; } else { for (int iterator=start;iterator<candidates.length;iterator++){ if (candidates[iterator]>target){ break; } current.add(candidates[iterator]); solve(candidates, iterator, target - candidates[iterator], current); current.pollLast(); } return; } } private LinkedList<Integer> copy(LinkedList<Integer> source){ LinkedList<Integer> dest=new LinkedList<>(); for (int i:source){ dest.add(i); } return dest; } }
另一个效率更高的算法:
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { return combinationSum(candidates, target, 0); } public List<List<Integer>> combinationSum(int[] candidates, int target, int start) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(candidates); for (int i = start; i < candidates.length; i++) { if (candidates[i] <target) { for (List<Integer> ar : combinationSum(candidates, target - candidates[i], i)) { ar.add(0, candidates[i]); res.add(ar); } } else if (candidates[i] == target) { List<Integer> lst = new ArrayList<>(); lst.add(candidates[i]); res.add(lst); } else break; } return res; } }
标签:
原文地址:http://www.cnblogs.com/bethunebtj/p/4824772.html