Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:
answer[i] % answer[j] == 0, oranswer[j] % answer[i] == 0
If there are multiple solutions, return any of them.
Example 1:
Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.
Example 2:
Input: nums = [1,2,4,8]
Output: [1,2,4,8]
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 2 * 109- All the integers in
numsare unique.
Approach - Bottom Up
- So first we sort then we check the condition and if this is the scenario to update then we also update the parent array which just stores the parent’s index
- Reason we use if statement instead of max is because we are doing other things too in the scenario where we fulfill the condition to update
O(n^2), O(n)
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp,1);
int[] parent = new int[n];
Arrays.fill(parent,-1);
int maxlen = 1, maxIndex = 0;
for (int i = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
if (nums[i]%nums[j] == 0) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
parent[i] = j;
}
}
}
if (dp[i] > maxlen) {
maxlen = dp[i];
maxIndex = i;
}
}
List<Integer> res = new ArrayList<>();
for (int curr = maxIndex; curr != -1; curr = parent[curr]) {
res.add(nums[curr]);
}
return res;
}
}Approach - Recursion - backtracking
- Two option if we take or not
O(2^n)
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
dfs(nums, -1, 0, new ArrayList<>());
return res;
}
private void dfs(int[] nums, int p, int c, List<Integer> tmp) {
if (c >= nums.length) {
if (tmp.size() > res.size())
res = new ArrayList<>(tmp);
return;
}
if (p == -1 || nums[c]%nums[p] == 0) {
tmp.add(nums[c]);
dfs(nums, c, c+1, tmp);
tmp.remove(tmp.size()-1);
}
dfs(nums, p, c+1, tmp);
}
}