首页 > 其他分享 >39. 组合总和(leetcode)

39. 组合总和(leetcode)

时间:2024-05-15 22:53:58浏览次数:16  
标签:39 target nums int res sum path leetcode 总和

https://leetcode.cn/problems/combination-sum/description/

两种搜索思路

一种是选或不选,搜索树是一颗二叉树
另一种是选哪个数,是一个n叉树

二叉

class Solution {
    
    List<List<Integer>> res = new ArrayList<>();
    int target;
    int[] nums;
    List<Integer> path= new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.nums=candidates;
        this.target=target;
        dfs(0,0);
        return res;
    }

    void dfs(int step,int sum)
    {
        if(step>=nums.length || sum>target)return;
        if(sum==target)
        {
            res.add(new ArrayList(path));
            return;
        }
        // 不选
        dfs(step+1,sum);
        // 选
        path.add(nums[step]);
        dfs(step,sum+nums[step]);
        path.remove(path.size()-1);
    }

}

 

n叉

class Solution {
    
    List<List<Integer>> res = new ArrayList<>();
    int target;
    int[] nums;
    List<Integer> path= new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.nums=candidates;
        this.target=target;
        dfs(0,0);
        return res;
    }

    void dfs(int startNum,int sum)
    {
        if(sum>target)return;
        if(sum==target)
        {
            res.add(new ArrayList(path));
            return;
        }
        // 多分支
        for(int i=startNum;i<=nums.length-1;i++)
        {
            path.add(nums[i]);
            dfs(i,sum+nums[i]);
            path.remove(path.size()-1);
        }
    }

}

 

标签:39,target,nums,int,res,sum,path,leetcode,总和
From: https://www.cnblogs.com/lxl-233/p/18194867

相关文章

  • 108. 将有序数组转换为二叉搜索树(leetcode)
    https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/要点是分割左右区间,并且分割时需要注意left和right相加可能会超过int,但是本题不需要classSolution{publicTreeNodesortedArrayToBST(int[]nums){//有返回值写法......
  • LeetCode 1992. Find All Groups of Farmland
    原题链接在这里:https://leetcode.com/problems/find-all-groups-of-farmland/description/题目:Youaregivena 0-indexed mxn binarymatrix land wherea 0 representsahectareofforestedlandanda 1 representsahectareoffarmland.Tokeepthelandor......
  • 错误解决 TypeError: __init__() got an unexpected keyword argument 'size'import l
    TypeError:__init__()gotanunexpectedkeywordargument'size'importlogging代码段如下importloggingimportosfromgensim.modelsimportword2veclogging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',level=logging.IN......
  • ROS学习日记:(报错)terminate called after throwing an instance of 'rclcpp::excepti
    论坛里的一个老哥给出答案https://discourse.ros.org/t/how-to-shutdown-and-reinitialize-a-publisher-node-in-ros-2/4090就是我在初始化环境前先初始化了节点autonode=std::make_shared<Static_tf_broadcaster>(argv);rclcpp::init(argc,argv);rclcpp::spin(nod......
  • [LeetCode] Find the Minimum Cost Array Permutation
    Youaregivenanarray nums whichisa permutation of [0,1,2,...,n-1].The score ofanypermutationof [0,1,2,...,n-1] named perm isdefinedas:score(perm)=|perm[0]-nums[perm[1]]|+|perm[1]-nums[perm[2]]|+...+|perm[n-1]-......
  • Structures Or Why Don't Things Fall Down (Reading)
    1BentmasonrycolumninSalisburyCathendral2Stressconcentrationatcracktip3'Aneurism'incylindricalballoon4Sectionofarterywalltissue5CorbelledvaultatTiryns6Simi-corbelledposterngateatTiryns7Clarebridge,Cambride(c......
  • flutter开发ios15出现name = 'io.flutter.1.raster', stop reason = signal SIGABRT崩
    1.问题描述为了适应ios上架要求,我们项目升级了flutter升级到3.19.6的,但是莫名其妙出现了这个崩溃,最关键的是没有关键的崩溃日志,不管是flutter侧还是ios原生侧都看不出哪行代码引起的2.问题排查首先,通过崩溃日志的关键字'io.flutter.1.raster',其实的raster就是光栅化的意思......
  • [Algorithm] Prim's Algorithm
    Prim'salgorithmisapopularmethodusedincomputerscienceforfindingaminimumspanningtreeforaconnected,undirectedgraph.Thismeansitfindsasubsetoftheedgesthatformsatreethatincludeseveryvertex,wherethetotalweightofall......
  • The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. T
    numba无法支持nopython错误解决错误:The'nopython'keywordargumentwasnotsuppliedtothe'numba.jit'decorator.TheimplicitdefaultvalueforthisargumentiscurrentlyFalse,butitwillbechangedtoTrueinNumba0.59.0.Seehttps://numb......
  • pinus老项目启动遇'Property connector does not exist on type UserRpc'报错
    跟示例项目对比过,配置代码并无出入,尝试在示例中新增远程调用connectorRemote可用,证明代码配置正确尝试在示例项目中使用工作项目的配置文件包括引用的模块文件目录列表如下 packagespluginspackage.jsonpackage-lock.jsontsconfig.jsonyarn.lock 示例安装模块后,运......