题目

类型:回溯

难度:中等

组合总和 - 图1

解题思路

组合总和 - 图2

代码

  1. class Solution {
  2. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. List<Integer> combine = new ArrayList<>();
  5. dfs(candidates, target, ans, combine, 0);
  6. return ans;
  7. }
  8. public void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int idx) {
  9. if (idx == candidates.length) {
  10. return;
  11. }
  12. if (target == 0) {
  13. ans.add(new ArrayList<>(combine));
  14. return;
  15. }
  16. // 直接跳过
  17. dfs(candidates, target, ans, combine, idx + 1);
  18. // 选择当前数
  19. if (target - candidates[idx] >= 0) {
  20. combine.add(candidates[idx]);
  21. dfs(candidates, target - candidates[idx], ans, combine, idx);
  22. combine.remove(combine.size() - 1);
  23. }
  24. }
  25. }