当前位置: 首页 > news >正文

力扣刷题494. 目标和

494. 目标和 - 力扣(LeetCode)

方法一,暴力dfs

直接进行深搜查找出所有的情况,缺点严重超时,只能过20个案例

留一下超时的

class Solution {
    //首先定义全局变量
    int[] abs = { +1, -1 };   //用来记录当前遍历的数的正负
    List<List<Integer>> list; //所有的结果
    List<Integer> res;         //记录当前的结果
 
    public int findTargetSumWays(int[] nums, int target) {
        //初始化
        res = new LinkedList<>();
        list = new ArrayList<>();
        dfs(nums, target, 0, 0);
        return list.size();
    }
    
    //可直接套用dfs模版
    public void dfs(int[] nums, int target, int sum, int index) {
        //如果满足条件则把当前的记录加入所有的结果当中
        if (res.size() == nums.length && sum == target) {
            list.add(new ArrayList<>(res));
            return;
        }
        //从index进行遍历,避免遍历重复数据
        for (int i = index; i < nums.length; i++) {
            //遍历数字的正负两种情况
            for (int j = 0; j < 2; j++) {
                int x = nums[i] * abs[j];
                res.add(x);
                dfs(nums, target, sum + x, i + 1);
                //剪枝,移除最后的数据
                res.remove(res.size() - 1);
            }
        }
    }
}

dfs优化: 可通过

因为这一道题不需要记录所有的方法,只需要统计一共的个数,所以可以进行优化

class Solution {
    //定义全局变量
    int count = 0;

    public int findTargetSumWays(int[] nums, int target) {
        count = 0;
        dfs(nums, target, 0, 0);
        return count;

    }

    public void dfs(int[] nums, int target, int sum, int index) {
        if (index == nums.length) {
            //这里的if不能合并,因为不管sum满不满足条件,都需要回溯
            if (sum == target) {
                count++;
            }
            return;
        }
        //当前数为正数
        dfs(nums, target, sum + nums[index], index + 1);
        //当前数为负数
        dfs(nums, target, sum - nums[index], index + 1);
    }
}

http://www.dtcms.com/a/98957.html

相关文章:

  • 【超详细教程】2025年3月最新Pytorch安装教程(同时讲解安装CPU和GPU版本)
  • Python3...(中国工信出版)读书笔记(1)python语言基础补充
  • 地下管线三维建模软件工具MagicPipe3D V3.6.1
  • Vue2 使用 v-if、v-else、v-else-if、v-show 以及 v-has 自定义指令实现条件渲染
  • [C++面试] 智能指针面试点(重点)续1
  • 飞书电子表格自建应用
  • JAVA反序列化深入学习(九):CommonsCollections7与CC链总结
  • 直接快速安装pytorch的cpu版本,在我的的 Python 3.8 + 虚拟环境 gdn 中安装
  • QT操作Word文档
  • The Rust Programming Language 学习 (七)
  • Windows 11系统下Kafka的详细安装与启动指南(JDK 1.8)
  • IvorySQL:兼容Oracle数据库的开源PostgreSQL
  • 【HTML 基础教程】HTML 链接
  • 多线程 - 线程安全引入
  • 什么是 实例化
  • Scala 数组
  • 排序算法2-选择排序
  • 07-SpringBoot3入门-整合druid连接池
  • Spring中的IOC及AOP概述
  • 高清电视 2.96| 免费高清电视直播
  • docker启动nacos+redis+seata
  • 【图像处理基石】什么是refocus?
  • 笔记本电脑更换主板后出现2203:System configuration is invalid,以及2201、2202系统错误的解决
  • AT24Cxx移植第三方库到裸机中使用
  • STM32单片机的桌面宠物机器人(基于HAL库)
  • Tomcat生产服务器性能优化
  • hi3516cv610编译sdk报错,解决方法
  • 深入理解Agentic Workflows
  • 迭代加深 IDE*
  • Git和GitCode使用(从Git安装到上传项目一条龙)