Combination Sum
来源:互联网 发布:照片flash制作软件 编辑:程序博客网 时间:2024/04/30 18:17
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { // Start typing your Java solution below // DO NOT write main() function if(candidates.length == 0) return null; Arrays.sort(candidates); return combinationSum(candidates, 0, target); } public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int start, int target) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>(); if(target <= 0) { if(target == 0) result.add(new ArrayList<Integer>()); return result; } for(int i = start; i < candidates.length; i++) { for(ArrayList<Integer> sub : combinationSum(candidates, i, target - candidates[i])) { sub.add(0, candidates[i]); set.add(sub); } } result.addAll(set); return result; } //no need to use hashset public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { // Start typing your Java solution below // DO NOT write main() function if(candidates.length == 0) return null; Arrays.sort(candidates); return combinationSum(candidates, 0, target); } public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int start, int target) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(target <= 0) { if(target == 0) result.add(new ArrayList<Integer>()); return result; } for(int i = start; i < candidates.length; i++) { for(ArrayList<Integer> sub : combinationSum(candidates, i, target - candidates[i])) { sub.add(0, candidates[i]); result.add(sub); } } return result; }