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]
一刷
题解:
先把数组排好序。首先要明确,若a<b且b%a==0 , b <c 且 c%b==0那么必然有c%a==0
我们设dp[i] 为最大的子集长度,更新的时候保存上一个的下标即可。
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if(nums.length == 0) return res;
Arrays.sort(nums);
int n = nums.length;
int[] dp = new int[n], index = new int[n];
Arrays.fill(dp, 1);
Arrays.fill(index, -1);
int max_index = 0, max_dp = 1;
for(int i=0; i<n; i++){
for(int j = i-1; j>=0; j--){
if(nums[i] % nums[j] == 0 && dp[j]+1>dp[i]){
dp[i] = dp[j]+1;
index[i] = j;
}
}
if(max_dp<dp[i]){
max_dp = dp[i];
max_index = i;
}
}
for(int i= max_index; i!=-1; i = index[i]){
res.add(nums[i]);
}
return res;
}
}
二刷
同上,但是要记住用index array作为指针(链表)这个特点
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<>();
int len = nums.length;
if(len==0) return res;
int[] dp = new int[len], index = new int[len];
int max_len = 1, max_index = 0;
Arrays.sort(nums);
Arrays.fill(dp, 1);
Arrays.fill(index, -1);
for(int i=0; i<len; i++){
for(int j=i-1; j>=0; j--){
if(nums[i]%nums[j] == 0 && dp[i]<dp[j]+1){
dp[i] = dp[j]+1;
index[i] = j;
}
}
if(dp[i]>max_len){
max_len = dp[i];
max_index = i;
}
}
for(int i=max_index; i>=0; i=index[i]){
res.add(nums[i]);
}
return res;
}
}