LeetCode六月挑战(6.13)Largest Divisible Subset Solution解题方案
Largest Divisible Subset
Solution
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.
1 2 3 4 5 6 7 8
| 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]
|
思路
这道题有一个数学思路在里面
对于一个有序数组,插入的数如果能整除数组中最大的数,那么也可以整除数组中其他的数。
因此我们要先将数组排序,然后设置一个路径储存数组记录添加元素的路径。
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { int n = nums.length; Arrays.sort(nums); int[] count = new int[n]; int[] road = new int[n]; int max = 0, index = -1; for (int i = 0; i < n; i++) { count[i] = 1; road[i] = -1; for (int j = i - 1; j >= 0; j--) { if (nums[i] % nums[j] == 0) { if (count[i] < 1 + count[j]) { count[i] = count[j] + 1; road[i] = j; } } } if (count[i] > max) { max = count[i]; index = i; } } List<Integer> result = new ArrayList<>(); while (index != -1) { result.add(nums[index]); index = road[index]; } return result; } }
|