Clean C++ O(n^2) DP solution


  • 0
    A
    class Solution {
    public:
        vector<int> largestDivisibleSubset(vector<int>& nums) {
            if (nums.empty())
                return {};
            
            sort(nums.begin(), nums.end(), greater<int>());
            int n = nums.size(), m = 1, idx = 0;
            vector<int> sizes(n, 1), prev(n, -1);
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < i; ++j) {
                    if (nums[j] % nums[i] == 0 && sizes[j] + 1 > sizes[i]) {
                        sizes[i] = sizes[j] + 1;
                        prev[i] = j;
                        if (sizes[i] > m) {
                            m = sizes[i];
                            idx = i;
                        }
                    }
                }
            }
            
            vector<int> ans;
            while (idx != -1) {
                ans.push_back(nums[idx]);
                idx = prev[idx];
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.