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: Input: [1,2,3] Output: [1,2] (of course, [1,3] will also be ok) Example 2: Input: [1,2,4,8] Output: [1,2,4,8]
假設有一組值惟一的正整數數組,找到元素最多的一個子數組,這個子數組中的任選兩個元素均可以構成Si % Sj = 0 或 Sj % Si = 0。面試
這題最核心的思路在於,假如知道前面k個數字所可以組成的知足題意的最長子數組,咱們就能夠知道第k+1個數字所能構成的最長子數組。只要這個數字是前面數字的倍數,則構成的數組的長度則是以前數字構成最長子數組加一。數組
這裏咱們使用了兩個臨時數組count和pre,分別用來記錄到第k個位置上的數字爲止可以構成的最長子數組,以及該子數組的前一個能夠被整除的值下標爲多少。微信
public List<Integer> largestDivisibleSubset(int[] nums) { int[] count = new int[nums.length]; int[] pre = new int[nums.length]; Arrays.sort(nums); int maxIndex = -1; int max = 0; for(int i = 0 ; i<nums.length ; i++) { count[i] = 1; pre[i] = -1; for(int j = i-1 ; j>=0 ; j--) { if(nums[i] % nums[j] == 0 && count[j] >= count[i]){ count[i] = count[j] + 1; pre[i] = j; } } if(count[i] > max) { max = count[i]; maxIndex = i; } } List<Integer> result = new ArrayList<Integer>(); while(maxIndex != -1){ result.add(nums[maxIndex]); maxIndex = pre[maxIndex]; } return result; }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~this