LeetCode 热题 HOT 100Java题解之39. 组合总和(击败了99.55%的用户)

2021/12/31 11:09:05

本文主要是介绍LeetCode 热题 HOT 100Java题解之39. 组合总和(击败了99.55%的用户),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目:

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

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

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


示例:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。


思路:

那么给出所有的可能性这一说的话,应该是用到回溯算法的

回溯可以具象为多叉树

横向靠for循环,纵向递归完成

还可以使用前缀和的形式,方便计算

还要剪枝,不然还有重复资源的浪费

复杂度:


时间复杂度:O(n) 

空间复杂度:O(N)

代码:

 public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        
        List<List<Integer>> res = new ArrayList<>();
        if(len == 0) return res;
        Arrays.sort(candidates);
        List<Integer> cur = new LinkedList<>();
        backtracking(candidates,target,cur,res,0,len);
        return res;

    }
    private void backtracking(int[] candidates, int target,List<Integer> cur,List<List<Integer>> res,int start,int len){
        
        if(target == 0){
            res.add(new ArrayList<Integer>(cur));
            return;
        }
        for(int i = start;i<len;++i){
            // 重点理解这里剪枝,前提是候选数组已经有序,
            if (target - candidates[i] < 0) {
                break;
            }

            cur.add(candidates[i]);
            backtracking(candidates,target-candidates[i],cur,res,i,len);
            cur.remove(cur.size()-1);
        }
    }

 



这篇关于LeetCode 热题 HOT 100Java题解之39. 组合总和(击败了99.55%的用户)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程