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]
一刷
題解:
先把數(shù)組排好序伍派。首先要明確,若a<b且b%a==0 , b <c 且 c%b==0那么必然有c%a==0
我們設(shè)dp[i] 為最大的子集長度诉植,更新的時候保存上一個的下標(biāo)即可。
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;
}
}