1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| import java.util.*;
public class _39组合总和 {
public List<List<Integer>> combinationSum_gov(int[] candidates, int target) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); List<Integer> combine = new ArrayList<Integer>(); dfs(candidates, target, ans, combine, 0); return ans; }
public void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int idx) { if (idx == candidates.length) { return; } if (target == 0) { ans.add(new ArrayList<Integer>(combine)); return; } dfs(candidates, target, ans, combine, idx + 1); if (target - candidates[idx] >= 0) { combine.add(candidates[idx]); dfs(candidates, target - candidates[idx], ans, combine, idx); combine.remove(combine.size() - 1); } }
public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); deal(new ArrayList<>(), candidates, target, 0); return res; }
private void deal(List<Integer> path, int[] candidates, int target, int idx) { if (target == 0 && !path.isEmpty()) { res.add(new ArrayList<>(path)); return; } else if (target < 0) { return; } for (int i = idx; i < candidates.length; i++) { int nextTarget = target - candidates[i]; if (nextTarget < 0) return;
path.addLast(candidates[i]); deal(path, candidates, nextTarget, i); path.removeLast(); } }
List<List<Integer>> res = new ArrayList<>();
public static void main(String[] args) { _39组合总和 combinationSum = new _39组合总和(); System.out.println(combinationSum.combinationSum(new int[]{2, 3, 6, 7}, 7)); } }
|