368. Largest Divisible Subset
Medium
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]
题意
给定数组nums,求数组中最大的子数组,子数组中两两元素可以整除
思路
动态规划
首先将nums排序,dp[i]含有nums[i]且nums[i]为子数组最大元素的子数组元素个数,递推式
dp[i] = max(dp[j] + 1), for all j in [0, i) st. nums[i] % nums[j] == 0
同时为了记录子数组,另外设一个回溯数组pre, pre[i]表示子数组中nums[i]的前一个元素在nums中的索引
代码
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int n = nums.length;
if (n == 0) {
return Collections.emptyList();
}
Arrays.sort(nums);
int i = 0, j = 0, ans = 0, index = 0;
int[] dp = new int[n], pre = new int[n];
Arrays.fill(dp, 1);
Arrays.fill(pre, -1);
for (i=1; i<n; ++i) {
for (j=i-1; j>=0; --j) {
if (nums[i] % nums[j] == 0) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
pre[i] = j;
}
}
}
if (dp[i] > ans) {
ans = dp[i];
index = i;
}
}
ArrayList<Integer> ret = new ArrayList<>();
while (index != -1) {
ret.add(nums[index]);
index = pre[index];
}
return ret;
}
}