zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Java -- Map
    Bootstrap -- 标签属性
    SQLServer -- 竟然默认不区分大小写
    ThinkPHP -- 问题
    ThinkPHP
    MVC-内容详情页显示内容
    未能加载文件或程序集“Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”或它的某一个依赖项。
    Random.Next获取随即数
    Razor语法小记
    VisualStudio自定义代码段_方法二
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5700578.html
Copyright © 2011-2022 走看看