Sponsored
Sponsored
This approach utilizes dynamic programming along with sorting to find the largest subset where each pair of elements is divisible by the other. The core idea is to sort the array, then use a dynamic programming array to keep track of the size of the largest divisible subset that ends at each element. We also maintain a path array to help reconstruct the subset.
Time Complexity: O(n^2), where n is the number of elements in the input set due to the nested loop.
Space Complexity: O(n), for arrays used to store intermediate results.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<int> LargestDivisibleSubset(int[] nums) {
6 int n = nums.Length;
7 if (n == 0) return new List<int>();
8 Array.Sort(nums);
9 List<int>[] dp = new List<int>[n];
10 for (int i = 0; i < n; i++) dp[i] = new List<int>();
11 for (int i = 0; i < n; i++) {
12 List<int> maxSubset = new List<int>();
13 for (int j = 0; j < i; j++) {
14 if (nums[i] % nums[j] == 0 && dp[j].Count > maxSubset.Count) {
15 maxSubset = new List<int>(dp[j]);
16 }
17 }
18 dp[i] = maxSubset;
19 dp[i].Add(nums[i]);
20 }
21 List<int> result = new List<int>();
22 foreach (var subset in dp) {
23 if (subset.Count > result.Count) result = subset;
24 }
25 return result;
26 }
27}
This C# solution involves sorting the array nums
and initializing a list array dp
where each index holds an integer list. Each element builds subsets from possible divisible elements before it. If nums[i]
is divisible by any previous element, it helps to grow the subset. The largest subset is then located within dp
and returned by comparing subset counts.
This approach leverages backtracking with pruning to explore subsets and constrain exploration using the divisibility constraint. It uses a sorted array to systematically explore subsets and prune paths early when constraints are no longer satisfied, allowing potentially faster exploration compared to the dynamic programming approach, especially in tightly constrained subsets.
Time and space complexities are challenging to define precisely for a backtracking solution as they depend on many factors including input distribution.
...