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
| class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> resultList = new ArrayList<>(); List<Integer> numList = new ArrayList<>(); dfs(resultList, numList, candidates, 0, 0, target); return resultList; }
private void dfs(List<List<Integer>> resultList, List<Integer> numList, int[] candidates, int i, int sum, int target) { if (sum > target) { return; } if (i == candidates.length) { if (sum == target) { resultList.add(new ArrayList<>(numList)); } return; }
dfs(resultList, numList, candidates, i + 1, sum, target);
numList.add(candidates[i]); dfs(resultList, numList, candidates, i, sum + candidates[i], target); numList.remove(numList.size() - 1); } }
|