• LeetCode-Largest Divisble Subset


    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:

    nums: [1,2,3]
    
    Result: [1,2] (of course, [1,3] will also be ok)
    

    Example 2:

    nums: [1,2,4,8]
    
    Result: [1,2,4,8]
    

    Credits:
    Special thanks to @Stomach_ache for adding this problem and creating all test cases.

    Analysis:

    Sort the array, then for nums[i], if nums[i] % nums[j] == 0, then nums[i] is in the largest divisible set of nums[j]. We just need to find out the largest subset of nums[i].

    Solution:

     1 public class Solution {
     2     public List<Integer> largestDivisibleSubset(int[] nums) {
     3         List<Integer> resList = new LinkedList<Integer>();        
     4         if (nums.length == 0) return resList;
     5 
     6         Arrays.sort(nums);
     7         int[] size = new int[nums.length];
     8         int[] pre = new int[nums.length];
     9 
    10         int maxSize = 0;
    11         int maxInd = -1;
    12 
    13         for (int i=0;i<nums.length;i++){
    14             int localMax = 0;
    15             int localInd = -1;
    16             for (int j=0;j<i;j++)
    17                 if (nums[i] % nums[j] == 0 && localMax < size[j]+1){
    18                     localMax = size[j]+1;
    19                     localInd = j;
    20                 }
    21             if (localInd == -1){
    22                 localMax = 1;
    23                 localInd = -1;
    24             } 
    25             size[i] = localMax;
    26             pre[i] = localInd;
    27             
    28 
    29             if (maxSize < localMax){
    30                 maxSize = localMax;
    31                 maxInd = i;
    32             }
    33         }
    34         
    35         resList.add(nums[maxInd]);
    36         int preInd = pre[maxInd];
    37         while (preInd != -1){
    38             maxInd = preInd;
    39             preInd = pre[maxInd];
    40             resList.add(nums[maxInd]);
    41         }
    42         Collections.reverse(resList);
    43         
    44         return resList;
    45     }
    46 }
  • 相关阅读:
    DirectSound学习笔记(7):缓冲区操作
    Firebird MsSQL Data Types比较
    插座上的Linux充电器.不..Marvell Plug Computer
    ASP.NET / 学习asp.net比较完整的流程
    P2P穿透UDP/TCP原理
    在C#中利用ActiveX控件进行视频采集
    ffmpeg快速命令使用
    Win7上帝模式
    DirectSound学习笔记(3):协作级别
    自己写的一个asp.netcookies购物车类
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5700578.html
Copyright © 2020-2023  润新知