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]
Answer:
Method: similar to Longest Increasing Subsequence. Using DP!
Time: O(n*n), Space:O(n)
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if(nums == null || nums.length==0){
return res;
}
int length = nums.length;
Arrays.sort(nums);
//dp[i] record the previous element index satisfy longest divisible sequence ending with nums[i].
int[] dp = new int[length];
//len[i] record the longest divisible sequence ending with nums[i] length.
int[] len = new int[length];
int maxLen = 1;
int maxLenFinalIndex = 0;
for(int i=0;i<length;i++){
dp[i] = i;
len[i] = 1;
for(int j=i-1;j>=0;j--){
if(nums[i] % nums[j] == 0){
if(len[j] + 1 > len[i]){
len[i] = len[j] + 1;
dp[i] = j;
}
}
}
if(len[i] > maxLen){
maxLen = len[i];
maxLenFinalIndex = i;
}
}
int index = maxLenFinalIndex;
int dpLen = maxLen;
while(index >= 0 && dpLen > 0){
res.add(nums[index]);
index = dp[index];
dpLen--;
}
Collections.reverse(res);
return res;
}
}
No comments:
Post a Comment