资讯专栏INFORMATION COLUMN

leetcode 40 Combination Sum II

li21 / 492人阅读

摘要:要求中的每一个元素在一个组合中只能被使用一次。输入候选数字集和目标数字结果集应当是想法首先这道题和题非常的相像。因此和题的解法相比,我们需要进行一次对于重复元素跳过的操作。

题目详情
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.

这道题的意思是,输入一个候选数字集(C)和一个目标数字(T).要求我们找出C中的不同元素组合,使得这些元素加和等于T。要求C中的每一个元素在一个组合中只能被使用一次。

For example, 输入候选数字集 [10, 1, 2, 7, 6, 1, 5] 和目标数字 8,
结果集应当是
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

想法

首先这道题和39题CombinationSum非常的相像。唯一的差别就在于这道题要求,每一个元素只能被使用一次。

因此和39题的解法相比,我们需要进行一次对于重复元素跳过的操作。

解法
    public List> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List> res = new ArrayList>();
        backtrack(res,new ArrayList(),candidates,target,0);
        return res;
    }
    public void backtrack(List> res,List tempList,int[] candidates,int remain,int start){
        if(remain < 0)return;
        if(remain == 0){
            res.add(new ArrayList<>(tempList));
        }else{
            for(int i=start;i start && candidates[i] == candidates[i-1]) continue;
                tempList.add(candidates[i]);
                backtrack(res,tempList,candidates,remain-candidates[i],i+1);
                tempList.remove(tempList.size()-1);
            }
        }
        

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

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

相关文章

  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0
  • Leetcode 相似题只有题号不含代码。

    找出string里的单词。 186. Reverse Words in a String II, 434. Number of Segments in a String combination类型题 77. Combinations 39. Combination Sum 40. Combination Sum II 216. Combination Sum III 494. Target S...

    StonePanda 评论0 收藏0
  • [LintCode/LeetCode] Combination Sum I & II

    摘要:和唯一的不同是组合中不能存在重复的元素,因此,在递归时将初始位即可。 Combination Sum I Problem Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T...

    ThreeWords 评论0 收藏0
  • [LeetCode] Combination Sum III | Combination Sum I

    摘要:此时,若也正好减小为,说明当前集合是正解,加入数组。两个无法得到正解的情况是在为,而不为时,当然已经无法得到正解,。在不为而却已经小于等于的情况下,此时仍要加入其它数以令为,而要加入的数都是到的正整数,所以已无法满足令为的条件,。 Combination Sum I & II: link Combination Sum III Problem Find all possible com...

    leiyi 评论0 收藏0
  • [Leetcode] Combination Sum 组合数之和

    摘要:深度优先搜索复杂度时间空间递归栈空间思路因为我们可以任意组合任意多个数,看其和是否是目标数,而且还要返回所有可能的组合,所以我们必须遍历所有可能性才能求解。这题是非常基本且典型的深度优先搜索并返回路径的题。本质上是有限深度优先搜索。 Combination Sum I Given a set of candidate numbers (C) and a target number (...

    GitCafe 评论0 收藏0

发表评论

0条评论

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