前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 368. Largest Divisible Subset分析代码

LeetCode 368. Largest Divisible Subset分析代码

作者头像
desperate633
发布2018-08-22 16:32:30
4450
发布2018-08-22 16:32:30
举报
文章被收录于专栏:desperate633desperate633

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. Example 1:

image.png Example 2:

image.png

分析

这里需要发现一个规律,就是如果result中已经有【1,2】,那么对于要新加进来的数,只要它能整除掉result中最大的数就可以,因为如果先把result按大小排序,那么显然result中最大的数可以整除其他比他小的数,那么新加来的数都可以整除最大的数,自然也可以其他数。所以我们先将数组排序。然后用一个数组记录添加的元素,也就是类似记录路径,这种方法记录路径的方法很常用,类似于并查集中的应用。具体看代码

代码

代码语言:javascript
复制
public class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n = nums.length;
        int[] count = new int[n];
        int[] pre = new int[n];
        Arrays.sort(nums);
        int max = 0, index = -1;
        for (int i = 0; i < n; i++) {
            count[i] = 1;
            pre[i] = -1;
            for (int j = i - 1; j >= 0; j--) {
                if (nums[i] % nums[j] == 0) {
                    if (1 + count[j] > count[i]) {
                        count[i] = count[j] + 1;
                        pre[i] = j;
                    }
                }
            }
            if (count[i] > max) {
                max = count[i];
                index = i;
            }
        }
        List<Integer> res = new ArrayList<>();
        while (index != -1) {
            res.add(nums[index]);
            index = pre[index];
        }
        return res;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.07.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档