[LeetCode] #39 组合总和

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。

candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是唯一的。

对于给定的输入,保证和为 target 的唯一组合数少于 150 个。

输入: candidates = [2,3,5], target = 8

输出: [[2,2,2,2],[2,3,3],[3,5]]

要求我们找满足条件的组合,可以使用回溯算法

类似于[LeetCode] #17 电话号码的字母组合

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        helper(candidates, target, res, list, 0);
        return res;
    }

    public void helper(int[] candidates, int target, List<List<Integer>> res, List<Integer> list, int index){
        if(index == candidates.length) return;
        if(target == 0){
            res.add(new ArrayList<Integer>(list));
            return;
        }
        helper(candidates, target, res, list, index + 1);
        if(target - candidates[index] >= 0){
            list.add(candidates[index]);
            helper(candidates, target- candidates[index], res, list, index);
            list.remove(list.size() - 1);
        }
    } 
}

或者依赖排序进行循环

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        Arrays.sort(candidates);
        helper(candidates, target, res, list, 0);
        return res;
    }
    private void helper(int[] candidates, int target, List<List<Integer>> res, List<Integer> list, int index) {
        if(target == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            if(target - candidates[i] >= 0) {
                list.add(candidates[i]);
                helper(candidates, target - candidates[i], res, list, i);
                list.remove(list.size()-1);
            } else {
                break;
            }
        }
    }
}

知识点:

总结:

走不通就退一步的枚举法就叫回朔法

寻找组合的问题可以使用回溯算法

posted @ 2021-10-14 14:13  1243741754  阅读(24)  评论(0编辑  收藏  举报