美文网首页
39. 组合总和

39. 组合总和

作者: justonemoretry | 来源:发表于2021-07-14 21:30 被阅读0次
image.png

解法

class Solution {

   public List<List<Integer>> res = new ArrayList<>();
    public  List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates, target, 0, 0);
        return res;
    }

    public void dfs(int[] candidates, int target, int sum, int startIndex) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
        }
        // 每层遍历,虽然每个可以重复取,但不能反着取,不然组合就重复了,如(2,3)(3,2)
        for (int i = startIndex; i < candidates.length; i++) {
            // 剪枝,大于target,后续也会大于
            if (sum + candidates[i] > target) {
                break;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            // 可以重复取,i不加1
            dfs(candidates, target, sum, i);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}

相关文章

  • 39. 组合总和

    39. 组合总和 很慢的dfs

  • 39. 组合总和

    39. 组合总和 https://leetcode-cn.com/problems/combination-sum...

  • 39. 组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • 39.组合总和

    题目给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所...

  • 39.组合总和

  • 39.组合总和

    Given a set of candidate numbers (candidates) (without du...

  • 39.组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • 39. 组合总和

    解题思路 典型的回溯法:递归跳出的条件return 满足题目条件将list加入容器else 未满足条件:for(遍...

  • 39. 组合总和

    题目描述 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates...

  • 39. 组合总和

    题目 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 can...

网友评论

      本文标题:39. 组合总和

      本文链接:https://www.haomeiwen.com/subject/dorupltx.html