摘要:題目解答參考的里的解法,核心思想從小到大,每一位數(shù)都能被比他大的數(shù)整除。對于從后往前看,找出每一個(gè)可以被它整除的數(shù)的數(shù)組,并更新它作為從這里開始,往后最大的,記錄下最大數(shù)組開始的地方,并把下一個(gè)數(shù)記在里找出最長的這個(gè)數(shù)組中的每一個(gè)數(shù)
題目:
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]
解答:
參考的discussion里的解法, 核心思想從小到大,每一位數(shù)都能被比他大的數(shù)整除。
public class Solution { public ListlargestDivisibleSubset(int[] nums) { List result = new ArrayList(); if (nums == null || nums.length == 0) return result; Arrays.sort(nums); int len = nums.length; int[] parent = new int[len]; int[] count = new int[len]; int max = 0, maxIndex = -1; //對于i從后往前看,找出每一個(gè)可以被它整除的數(shù)的數(shù)組,并更新它作為從這里開始,往后最大的subset,記錄下最大數(shù)組開始的地方,并把下一個(gè)數(shù)記在parent里 for (int i = len - 1; i >= 0; i--) { for (int j = i; j < len; j++) { if (nums[j] % nums[i] == 0 && count[i] < count[j] + 1) { count[i] = count[j] + 1; parent[i] = j; if (count[i] > max) { max = count[i]; maxIndex = i; } } } } for (int i = 0; i < max; i++) { //找出最長的這個(gè)數(shù)組中的每一個(gè)數(shù) result.add(nums[maxIndex]); maxIndex = parent[maxIndex]; } return result; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/64946.html
摘要:讓數(shù)組從小到大排序。因?yàn)槿绻粋€(gè)數(shù)能被加到這個(gè)中的話,說明這個(gè)數(shù)能被這個(gè)中的最大的數(shù)整除。同樣可以用一個(gè)數(shù)組來記錄之前搜索過的。,表示的是我們搜索的路徑是從到。初始化這個(gè)位置是頭結(jié)點(diǎn)。說明是,并沒有是當(dāng)前最大的里的最大值。 LeetCode[368] Largest Divisible Subset Given a set of distinct positive integers,...
368. Largest Divisible Subset 題目鏈接:https://leetcode.com/problems... dp記錄最大的長度,加parent指針存路徑。dp方程是:dp[i] = max(dp[j]) + 1, if nums[i]%nums[j] == 0 public class Solution { public List largestDivisibl...
摘要:題目要求假設(shè)有一組值唯一的正整數(shù)數(shù)組,找到元素最多的一個(gè)子數(shù)組,這個(gè)子數(shù)組中的任選兩個(gè)元素都可以構(gòu)成或。只要這個(gè)數(shù)字是前面數(shù)字的倍數(shù),則構(gòu)成的數(shù)組的長度則是之前數(shù)字構(gòu)成最長子數(shù)組加一。 題目要求 Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj)...
摘要:刷題繼續(xù)上一期和大家分享了前道題,今天繼續(xù)來刷解法一解法二解法三解法一解法二解法三解法四解法一解法二解法三解法一解法二解法三解法一解法二解法一解法一解法二解法一解法二解法三解法四解法一解法一源代碼下載這十道題的 刷題繼續(xù) 上一期和大家分享了前10道題,今天繼續(xù)來刷11~20 Question 11: Write a program which accepts a sequence o...
Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...
閱讀 1014·2023-04-25 15:42
閱讀 3608·2021-11-02 14:38
閱讀 2901·2021-09-30 09:48
閱讀 1443·2021-09-23 11:22
閱讀 3405·2021-09-06 15:02
閱讀 3199·2021-09-04 16:41
閱讀 617·2021-09-02 15:41
閱讀 2026·2021-08-26 14:13