栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣 40. 组合总和 II

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣 40. 组合总和 II

题目

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

注意:解集不能包含重复的组合。

示例

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1:回溯 Java实现

⭐关键:

if (i > 0 && candidates[i] == candidates[i-1] && i != start) continue;

class Solution {
    List> res = new ArrayList<>();
    Map, List> map = new HashMap<>();
    int sum = 0;
    public List> combinationSum2(int[] candidates, int target) {
         linkedList track = new linkedList<>();
         Arrays.sort(candidates);
         track_back(candidates, target, 0, track);
         return res;
    }

    public void track_back(int[] candidates, int target, int start, linkedList track){
        if (sum == target){
            List var = new ArrayList<>(track);
            res.add(var);
            return;
        } else if (sum > target) return;

        for (int i = start; i < candidates.length; i++){
        	//⭐关键的一步
            if (i > 0 && candidates[i] == candidates[i-1] && i != start) continue;
            track.addLast(candidates[i]);
            sum += candidates[i];

            track_back(candidates, target, i + 1, track);

            sum -= candidates[i];
            track.removeLast();
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/490146.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号