资讯专栏INFORMATION COLUMN

leecode 39 Combination Sum

yhaolpz / 538人阅读

摘要:我们需要找出中的数字的不同组合,使得每一种组合的元素加和为。输入的候选集和目标数字结果集是想法这道题采取了递归的思路。每次将一个元素加入的时候,判断是否满足中的元素加和等于,如果等于,直接将加入最终返回的结果集。

题目详情
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.

输入一个不含重复数字的候选的数字集(C)和一个目标数字(T)。我们需要找出c中的数字的不同组合,使得每一种组合的元素加和为T。

For example, 输入的候选集[2, 3, 6, 7]和目标数字7,
结果集是:
[[7],[2, 2, 3]]

想法

这道题采取了递归的思路。

递归方法的输入参数分别是,最终需要返回的结果list,暂存元素list,候选集,离目标元素和的差值,和开始遍历的起点。

每次将一个元素加入templist的时候,判断是否满足templist中的元素加和等于target,如果等于,直接将templist加入最终返回的结果集res。如果加和大于target,那么就没必要继续递归往templist中增加元素了。如果加和小于list,那么继续递归加入新的元素。

解法
    public List> combinationSum(int[] nums, int target) {
        List> res = new ArrayList>();
        Arrays.sort(nums);
        backtrack(res,new ArrayList<>(),nums,target,0);
        return res;
    }
    public void backtrack(List> res,List temp,int[] nums,int remain,int start){
        if(remain <0)return;
        if(remain == 0)res.add(new ArrayList<>(temp));
        else{
            for(int i=start;i           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68502.html

相关文章

  • leetcode-39-Combination Sum

    摘要:分为每次从里边循环所有数,已有值减去所有数,新值作为已有值,继续处理。遇到返回保存,负数去掉 39. Combination SumDescriptionHintsSubmissionsDiscussSolutionGiven a set of candidate numbers (C) (without duplicates) and a target number (T),find...

    Drummor 评论0 收藏0
  • leetcode39 combination sum

    摘要:在这道题中,我结合了递归的思想来。就是将当前的值作为一个潜在的结果值加入一个结果数组将数组作为当前结果传入下一轮递归。 题目要求 Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the ca...

    luoyibu 评论0 收藏0
  • leetcode40 combination sum 2

    摘要:参考思路和非常类似,只是这里需要增加进行重复处理的部分。题目要求题目中新添的要求包括数组中存在重复值,而且数组中每个值只可以使用一次。需要注意的是,既然数组中存在重复的值,就要注意可能会将重复的情况加入结果数组。 参考 思路和leetcode39 combination sum 非常类似,只是这里需要增加进行重复处理的部分。请参考我对leetcode39进行解答的这篇博客。 题目要求 ...

    Code4App 评论0 收藏0
  • LeetCode偶尔一题 —— 39. Combination Sum(回溯算法系列)

    摘要:输入输出分析题目由于我们需要找到多个组合,简单的使用循环肯定是不行的,这时候我们可以使用回溯算法来解决这个问题。用回溯算法解决问题的一般步骤针对所给问题,定义问题的解空间,它至少包含问题的一个最优解。 题目描述 Given a set of candidate numbers (candidates) (without duplicates) and a target number ...

    linkin 评论0 收藏0
  • leetcode 40 Combination Sum II

    摘要:要求中的每一个元素在一个组合中只能被使用一次。输入候选数字集和目标数字结果集应当是想法首先这道题和题非常的相像。因此和题的解法相比,我们需要进行一次对于重复元素跳过的操作。 题目详情 Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C...

    li21 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<