39. 组合总和

2021-07-14  本文已影响0人  justonemoretry
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);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读