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
| package algorithm;
import java.util.ArrayList; import java.util.List;
public class CombinationSum {
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>(); List<Integer> element = new ArrayList<>(); dfs(result, element, candidates, target, 0); return result; }
private static void dfs(List<List<Integer>> result, List<Integer> element, int[] candidates, int target, int index) {
if (target == 0) { // 注意因为会回溯,所以需要新建一个,回溯会改变集合 result.add(new ArrayList<>(element)); return; } if (index == candidates.length) { return; } // 跳过index dfs(result, element, candidates, target, index + 1); // 使用当前index if (target - candidates[index] >= 0) { element.add(candidates[index]); dfs(result, element, candidates, target - candidates[index], index); element.remove(element.size() - 1); } }
public static void main(String[] args) {
int[] candidates = new int[]{2,3,6,7}; int targe = 7; System.out.println(combinationSum(candidates, targe));
candidates = new int[]{2,3,5}; targe = 8; System.out.println(combinationSum(candidates, targe)); } }
|