368. Largest Divisible Subset

Medium (Trung bình) C++ 🔗 Xem trên LeetCode

📋 Đề Bài

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, or
  • answer[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 <= 1000
  • 1 <= nums[i] <= 2 * 109
  • All the integers in nums are unique.

🧠 Thuật Toán & Kỹ Thuật

Dynamic Programming (Quy hoạch động)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

C++ 0368-largest-divisible-subset.cpp
class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        const int n = nums.size();
        vector<int> dp(n, 1);
        int maxLen = 0;
        
        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = max(dp[i], dp[j] + 1);
                }
            }
            maxLen = max(maxLen, dp[i]);
        }
        
        int j = 0;
        
        for (int i = n - 1; i >= 0; --i) {
            if (dp[i] == maxLen) {
                j = i;
                break;
            }
        }
        
        vector<int> ans = {nums[j]};
        j--, maxLen--;
        
        for (int i = j; i >= 0; --i) {
            if (dp[i] == maxLen and ans.back() % nums[i] == 0) {
                ans.push_back(nums[i]);
                maxLen--;
            }
        }
        
        reverse(ans.begin(), ans.end());
        
        return ans;
    }
};