LeetCode40题: 组合总和 II(原创)

news2024/9/19 10:35:54

【题目描述】

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

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

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

示例 1:

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

示例 2:

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

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

【题目链接】. - 力扣(LeetCode)

【解题代码】

package dp;

import java.util.*;


public class CombinationSum2 {
    private static List<List<Integer>> numLists = new ArrayList<>();
    private static List<Integer> numList = new ArrayList<>();

    public static void main(String[] args) {
        //int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        //int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        int[] candidates = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2};
        System.out.println("开始计算。。。");
        long start = System.currentTimeMillis();
        List<List<Integer>> numLists = new CombinationSum2().combinationSum(candidates, 8);
        System.out.println("运行时长:" + (System.currentTimeMillis() - start) + "ms");
        for (List<Integer> numList : numLists) {
            System.out.println(Arrays.toString(numList.toArray()));
        }

    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        doCombinationSum(candidates, 0, target);
        HashSet set = new HashSet<>(numLists);
        numLists.clear();
        numLists.addAll(set);
        return numLists;
    }

    private void doCombinationSum(int[] candidates, int n, int target) {
        if (target == 0) {
            numLists.add(new ArrayList<>(numList));
        } else if (n < candidates.length) {
            doCombinationSum(candidates, n + 1, target);
            if (target >= candidates[n]) {
                int i = n + 1;
                int delta = candidates[n];
                numList.add(candidates[n]);
                while (i < candidates.length && candidates[i] == candidates[n] && target >= delta) {
                    delta += candidates[i];
                    numList.add(candidates[n]);
                    i++;
                }
                doCombinationSum(candidates, i, target - delta);
                for (int j = i; j > n; j--) {
                    numList.remove(numList.size() - 1);
                }
            }
        }
    }

    private void doCombinationSum1(int[] candidates, int n, int target) {
        if (target == 0) {
            numLists.add(new ArrayList<>(numList));
        } else if (n < candidates.length) {
            if (target >= candidates[n]){
                doCombinationSum(candidates, n + 1, target);
                numList.add(candidates[n]);
                doCombinationSum(candidates, n + 1, target - candidates[n]);
                numList.remove(numList.size() - 1);
            }
        }
    }
}

【解题思路】

        一开始拿到题目,以为和之前解析的LeetCode39题: 组合总和(原创)-CSDN博客差不多,直接把之前代码拷贝,做了一些排序,去重相关的修改,提交运行成功,代码如下:

class Solution {
    private List<List<Integer>> numLists = new ArrayList<>();
    private List<Integer> numList = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        doCombinationSum(candidates, 0, target);
        HashSet set = new HashSet<>(numLists);
        numLists.clear();
        numLists.addAll(set);
        return numLists;
    }

     private void doCombinationSum(int[] candidates, int n, int target) {
        if (target == 0) {
            numLists.add(new ArrayList<>(numList));
        } else if (n < candidates.length) {
            doCombinationSum(candidates, n + 1, target);
            if (target >= candidates[n]) {
                numList.add(candidates[n]);
                doCombinationSum(candidates, n + 1, target - candidates[n]);
                numList.remove(numList.size() - 1);
            }
        }
    }
}

以为和之前题目一样,没什么问题了,但已提交出乎意料,系统跑到第172个测试用例:30个重复的1时,提示超出时间限制:

自己拿这个测试用例在本地跑了下,运行时长7111ms,确实性能有问题。那如何优化,当时思考和实现了多次没有头绪,于是放弃了。一直到今天想尽量清理提交未通过时的题目时,对此题思考了一会,突然有了思路:对于重复的数据,全选的情况其实是唯一,那何不一次性将所有的重复数据加入结果集中,而避免一个一个的递归。这样性能应该能大大提升。想到一点,感觉有希望,如实按照这个思路快速修改代码,果然所有测试用例都过关了

虽然数据还不是特别好,但终于算过关了。

【解题步骤】

  1. 在解题类里定义两个静态链表对象:一个numList存储当前组合数据列表,一个numLists存储所有组合列表
    private static List<List<Integer>> numLists = new ArrayList<>();
    private static List<Integer> numList = new ArrayList<>();
  2. 定义一个回溯递归函数doCombinationSum,参数包括整数数组 candidates,当前索引值n,目标值targe
     private void doCombinationSum(int[] candidates, int n, int target) {
  3. 因为存在重复数据,先将所有数据进行排序
    Arrays.sort(candidates);
  4. 如果目标值target为0,说明当前候选数字序列numList满足要求,添加到结果集numLists
    if (target == 0) {
        numLists.add(new ArrayList<>(numList));
    } 
  5. 如果数组遍历还没遍历完,首先选择不选择当前数字,直接递归处理下一个索引数字即可
    } else if (n < candidates.length) {
        doCombinationSum(candidates, n + 1, target, numList, numLists);
  6.  接下来,如果当前数字小于等于目标值target,那么尝试一次性选择所有相同数值的数字,并将此数据序列添加到候选数字序列,将目标值target去数值后,并从当前索引重复递归,递归完毕,回溯将此数据序列从候选数字序列中删
    if (target >= candidates[n]) {
        int i = n + 1;
        int delta = candidates[n];
        numList.add(candidates[n]);
        while (i < candidates.length && candidates[i] == candidates[n] && target >= delta) {
            delta += candidates[i];
            numList.add(candidates[n]);
            i++;
        }
        doCombinationSum(candidates, i, target - delta);
        for (int j = i; j > n; j--) {
            numList.remove(numList.size() - 1);
        }
    }

【思考总结】

  1. 这一题是LeetCode39题: 组合总和(原创)-CSDN博客的姊妹题,其关键解题思路:对于重复的数据,全选的情况其实是唯一,那何不一次性将所有的重复数据加入结果集中,而避免一个一个的递归。这样性能应该能大大提升。
  2. 了解掌握回溯算法定义:回溯算法定义 回溯算法,是一种选优搜索法,又称为试探法,按选优条件向前搜索以达到目标。 回溯算法简要说:但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法。 而满足回溯条件的某个状态的点称为“回溯点”。
  3. 回溯与递归的区别:递归的基本性质就是函数调用,在处理问题的时候,递归往往是把一个大规模的问题不断地变小然后进行推导的过程。 回溯则是利用递归的性质,从问题的起始点出发,不断地进行尝试,回头一步甚至多步再做选择,直到最终抵达终点的过程;
  4. LeetCode解题之前,一定不要看题解,看了就“破功”了!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1965603.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

安装MongoDB UI客户端工具:mongodb-compass-1.40.2-win32-x64.msi

文章目录 1、安装 mongodb-compass-1.40.2-win32-x64.msi2、安装后配置链接地址&#xff1a; 1、安装 mongodb-compass-1.40.2-win32-x64.msi 2、安装后配置链接地址&#xff1a;

读书其实并没有那么大的作用

开场白 Hey&#xff0c;书虫们和生活探索者们&#xff01;今天我们来聊聊一个老生常谈却又常谈常新的话题——读书。有人说&#xff0c;读书能改变命运&#xff0c;但也有人说&#xff0c;读书不过是生活的调味品。那么&#xff0c;读书到底有啥用&#xff1f;让我们一起来扒一…

卫星导航系统的应用领域与发展前景

当人们提到卫星导航系统&#xff0c;往往会联想到车载导航仪或手机上的地图应用。然而&#xff0c;卫星导航系统的应用远不止于此&#xff0c;它在许多领域都发挥着重要作用。下面将介绍几个卫星导航系统的应用领域及其发展前景。首先是海洋航行安全领域。在过去&#xff0c;海…

搜维尔科技:Haption:对于遥控机器人来说,触觉技术是什么

力反馈遥控机器人有哪些好处&#xff1f; 遥控机器人是机器人技术领域的一个领域&#xff0c;主要涉及远距离控制半自主机器人。它被定义为遥操作和远程呈现的结合。第一部分&#xff0c;遥控操作&#xff0c;使操作员能够远程控制机器人。第二部分&#xff0c;远程呈现&#…

全网最适合入门的面向对象编程教程:29 类和对象的Python实现-断言与防御性编程和help函数的使用

全网最适合入门的面向对象编程教程&#xff1a;29 类和对象的 Python 实现-断言与防御性编程和 help 函数的使用 摘要&#xff1a; 在 Python 中&#xff0c;断言是一种常用的调试工具&#xff0c;它允许程序员编写一条检查某个条件。本文主要介绍了断言的应用场景和特点以及 …

jmeter-beanshell学习13-设置等待时间

接口测试时候&#xff0c;如果交易成功&#xff0c;一切正常&#xff0c;如果交易失败&#xff0c;可能会涉及回滚。之前写的都是做完交易&#xff0c;紧接着去查库&#xff0c;就可能遇到还没回滚完成&#xff0c;已经查完库了&#xff0c;查出来的数据不准确。既然写beanshel…

前端低代码必备:FrontendBlocks 4.0版本重磅发布,助力Uniapp-X原生APP开发

项目介绍 本软件是一款强大的所见即所得前端页面设计器&#xff0c;是低代码开发领域的基础设施&#xff0c;生成的代码不依赖于任何框架&#xff0c;实测可以将前端布局工作的耗时减少80%以上&#xff0c;最关键的是&#xff0c;它实现了人人都可以写前端页面的梦想。 不用写…

相似度计算方法

一、相似度计算方法 相似度算法是计算两个或多个对象之间相似程度的方法&#xff0c;这些对象可以是文本、图像、音频等不同类型的数据。在计算机科学、信息检索、推荐系统、数据挖掘等领域中&#xff0c;相似度算法具有广泛的应用。 二、应用场景 搜索引擎&#xff1a;用于文…

实验3-2 计算符号函数的值

//实验3-2 计算符号函数的值#include <stdio.h> #include <math.h>int main() {int n 0;scanf("%d",&n);int sign;if(n > 0)sign1;else if(n < 0)sign-1;else sign0;printf("sign(%d) %d", n, sign); }

0731作业+梳理

一、作业 1.用两个进程完成拷贝 代码&#xff1a; #include<myhead.h> //定义一个求文件长度函数 int line(const char *pd1,const char *pd2) { int fd1 -1; int fd2 -1; //以只读形式打开源文件 if((fd1 open(pd1,O_RDONLY))-1) { p…

人最大的内耗,是不肯放过自己

你是否也有过这样的经历&#xff1a; 对别人漫不经心的一句话就琢磨很久&#xff0c;生怕产生隔阂&#xff1b;对自己曾经犯过的错误念念不忘&#xff0c;始终无法释怀&#xff1b;工作里出现一点小失误&#xff0c;便整宿翻来覆去难以入眠......每天陷在迷茫、焦虑、恐慌的情…

matlab 2022a 安装教程

下载安装包 &#xff0c;多个压缩包&#xff0c;依次解压 第一步 第二步 2、输入文件安装密钥&#xff1a;“50874-33247-14209-37962-45495-25133-28159-33348-18070-60881-29843-35694-31780-18077-36759-35464-51270-19436-54668-35284-27811-01134-26918-26782-54088” 50…

二百四十九、Linux——修改ulimit限制数量:打开文件的最大数量和用户进程的最大数量

一、目的 在安装OceanBase时脚本报错 [ERROR] OBD-1007: (127.0.0.1) The value of the ulimit parameter "open files" must not be less than 20000 (Current value: 1024), Please execute echo -e "* soft nofile 20000\n* hard nofile 20000" >&…

TiDB系列之:TiCDC同步TiDB数据库数据到Kafka集群Topic

TiDB系列之&#xff1a;TiCDC同步TiDB数据库数据到Kafka集群Topic 一、Changefeed 概述Changefeed 状态流转操作 Changefeed 二、同步数据到Kafka创建同步任务&#xff0c;复制增量数据 KafkaSink URI 配置 kafka最佳实践TiCDC 使用 Kafka 的认证与授权TiCDC 集成 Kafka Connec…

移动硬盘有盘符却难启?数据恢复全攻略

现象解析&#xff1a;移动硬盘有盘符打不开的谜团 在日常的数字生活中&#xff0c;移动硬盘作为数据存储与传输的重要工具&#xff0c;扮演着不可或缺的角色。然而&#xff0c;当用户遇到移动硬盘在系统中显示盘符却无法正常访问的情况时&#xff0c;无疑会令人感到焦头烂额。…

hackme漏洞打靶

1.安装好靶机后点击启动进入这样的一个页面 然后我们就要去找这个靶机的IP地址&#xff0c;首先将该虚拟机网卡设置为net模式&#xff0c;然后在物理机中查看自己ip&#xff0c;看看vmnet8的地址c段是什么&#xff0c;我这里是209&#xff0c;然后用工具去扫描该c段下哪个ip开放…

离乡路远,归途已断

首发于我的个人独立博客 guqing’s blog 每次踏上回乡的路&#xff0c;我心中总有一种难以言喻的情感。故乡&#xff0c;那片孕育我成长的土地&#xff0c;依然静静地躺在那儿&#xff0c;似乎未曾改变。 然而&#xff0c;每次回到家乡&#xff0c;我都能感受到微妙的变化&…

探索七款前沿UI设计软件:创新与实践

之前我们分享了制作原型的有用工具。制作完原型后&#xff0c;我们需要优化界面&#xff0c;这就是 UI 设计师的任务了。UI 设计软件对设计师来说非常重要。UI 设计工具的使用是否直接影响到最终结果的质量&#xff0c;所以有人会问&#xff1a;UI 界面设计使用什么软件&#x…

【切面编程】自定义注解实现操作日志

创建一个项目工程 引入相关依赖 <!-- aop切面 --> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- lombok --> <dependency><gro…

24导游证报名照片要求是什么❓整理好了❗

24导游证报名照片要求是什么❓整理好了❗ 导游资格考试今天开始报名啦&#xff01; ⚠️考生们注意&#xff0c;需要上传免冠证件照、身份证扫描件、学历证明等照片信息&#xff01; ⚠️这里需要注意一下上传的照片文件信息规格&#xff0c;否则上传失败&#xff0c;无法完…