🌕 39. 组合总和

吞佛童子2022年6月9日
  • algorithm
  • backtrace
大约 1 分钟

🌕 39. 组合总和

难度: 🌕

问题描述

img_7.png


解法 1

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // 思路:
        // 无重复元素 + 可重复选取
        // 回溯
        LinkedList<Integer> path = new LinkedList<>();
        int len = candidates.length;
        mySol(candidates, target, len, 0, 0, path);
        return res;
    }

    private void mySol(int[] array, int target, int len, int index, int sum, LinkedList<Integer> path) {
        // 递归终止条件判断
        if(sum > target) {
            return;
        }
        if(sum == target) {
            res.add(new LinkedList<>(path));
            return;
        }
        if(index > len) {
            return;
        }
        // index <= len && sum < target
        for(int i = index; i < len; i ++) {
            path.addLast(array[i]);
            mySol(array, target, len, i, sum + array[i], path);
            path.removeLast();
        }
    }
}

输出 1

img_8.png


解法 2 - 排序 + 剪枝优化

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // 思路:
        // 无重复元素 + 可重复选取
        // 回溯 + 剪枝
        LinkedList<Integer> path = new LinkedList<>();
        int len = candidates.length;
        Arrays.sort(candidates); // 排序优化
        mySol(candidates, target, len, 0, 0, path);
        return res;
    }

    private void mySol(int[] array, int target, int len, int index, int sum, LinkedList<Integer> path) {
        // 递归终止条件判断
        if(sum > target) {
            return;
        }
        if(sum == target) {
            res.add(new LinkedList<>(path));
            return;
        }
        if(index > len) {
            return;
        }
        // index <= len && sum < target
        for(int i = index; i < len; i ++) {
            if(sum + array[i] > target) {
                return;
            }
            path.addLast(array[i]);
            mySol(array, target, len, i, sum + array[i], path);
            path.removeLast();
        }
    }
}

输出 2

img_9.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou