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

【Leetcode 每日一题】368. 最大整除子集

问题背景

给你一个由 无重复 正整数组成的集合 n u m s nums nums,请你找出并返回其中最大的整除子集 a n s w e r answer answer,子集中每一元素对 ( a n s w e r [ i ] , a n s w e r [ j ] ) (answer[i], answer[j]) (answer[i],answer[j]) 都应当满足:

  • a n s w e r [ i ]   %   a n s w e r [ j ] = 0 answer[i] \ \% \ answer[j] = 0 answer[i] % answer[j]=0,或
  • a n s w e r [ j ]   %   a n s w e r [ i ] = 0 answer[j] \ \% \ answer[i] = 0 answer[j] % answer[i]=0
    如果存在多个有效解子集,返回其中任何一个均可。

数据约束

  • 1 ≤ n u m s . l e n g t h ≤ 1000 1 \le nums.length \le 1000 1nums.length1000
  • 1 ≤ n u m s [ i ] ≤ 2 × 1 0 9 1 \le nums[i] \le 2 \times 10 ^ 9 1nums[i]2×109
  • n u m s nums nums 中的所有整数 互不相同

解题过程

生成答案的过程,应当是在已经形成的子集中尝试添加新元素,最终结果是从规模更小的解转移而来,用动态规划解决,类似 最长递增子序列。

具体实现

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        int[] memo = new int[n];
        int[] from = new int[n];
        Arrays.fill(from, -1);
        int res = 0;
        int index = 0;
        for (int i = 0; i < n; i++) {
            int cur = dfs(i, nums, memo, from);
            if (cur > res) {
                res = cur;
                index = i;
            }
        }
        List<Integer> path = new ArrayList<>(res);
        for (int i = index; i >= 0; i = from[i]) {
            path.add(nums[i]);
        }
        return path;
    }

    private int dfs(int i, int[] nums, int[] memo, int[] from) {
        if (memo[i] > 0) {
            return memo[i];
        }
        int res = 0;
        for (int j = 0; j < i; j++) {
            if (nums[i] % nums[j] != 0) {
                continue;
            }
            int cur = dfs(j, nums, memo, from);
            if (cur > res) {
                res = cur;
                from[i] = j;
            }
        }
        return memo[i] = res + 1;
    }
}

相关文章:

  • 设计模式简述(十一)装饰器模式
  • Android studio局域网屏幕共享(旧手机可以用来当监控啦)
  • 虚幻5学习笔记,疑点
  • 力扣刷题-热题100题-第32题(c++、python)
  • 玩转大语言模型——使用华为官方MindIE-Server镜像方式部署DeepSeek模型
  • 编程基础 0 到 1 1768. 交替合并字符串
  • 蓝桥杯 日期统计(刷题笔记)
  • C++多线程编码二
  • 软件学报 2024年 区块链论文 录用汇总 附pdf下载
  • httpx模块的使用
  • Java中的同步和异步
  • 语法: result=ldexp (value, exp);
  • PHP 安全 E-mail
  • MatterGen-加速材料发现
  • 现代Web应用中的时光机器:深入解析撤销/重做功能的艺术与科学
  • Mac OS 禁用 SIP 系统完整性保护
  • Java学习总结-多线程-三种创建方法
  • Qt 音乐播放器项目
  • C语言:转置矩阵
  • vue封装一个toast(vue-toastification)弹窗在拦截器js中调用
  • 桂林北站图片/管理培训机构
  • 微信小程序分销系统/南京seo公司教程
  • 女孩学网站开发和动漫设计/苏州seo网络推广
  • 成都网站建设xhbrand/官网seo是什么
  • 手机网站与普通网站的区别/百度竞价排名事件分析
  • 网站建设的功能定位/廊坊seo排名优化