0
点赞
收藏
分享

微信扫一扫

组合总和-Leetcode

yeamy 2022-04-19 阅读 55
javaleetcode

title: 组合总和-Leetcode
date: 2022-04-19 09:47:00
tags: 每天进步一点点系列


每日题目

题目:组合总和

示例:

代码:

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res =  new ArrayList<>();
        //如果数组为空,直接返回空结果
        if(candidates==null||candidates.length==0){
            return res;
        }
        //先排序
        Arrays.sort(candidates);
        //dfs
        dfs(candidates,target,0,new ArrayList<>(),res);
        return res;
    }

    public void dfs(int[] candidates,int target ,int start,List<Integer> list,List<List<Integer>> res){
        //如果目标值为0,说明已经找到一个组合,添加到结果集中
        if(target==0){
            res.add(new ArrayList<>(list));
            return;
        }
        //遍历数组
        for (int i = start; i < candidates.length; i++) {
            //如果当前值大于目标值,则不需要继续遍历
            if(candidates[i]>target){
                return;
            }
            list.add(candidates[i]);
            //更新目标值和起始位置
            dfs(candidates,target-candidates[i],i,list,res);
            //回溯,删除当前值
            list.remove(list.size()-1);
        }


    }
}

每日单词

在这里插入图片描述

看完如果对你有帮助,感谢点击下面的一键三连支持!
[哈哈][抱拳]

请添加图片描述在这里插入图片描述
加油!

共同努力!

Keafmd

举报

相关推荐

0 条评论