C++ solution with O(n^2) complexity


  • 0
    L
    class Solution {
    public:
        vector<int> largestDivisibleSubset(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            vector<int> result;
            vector<vector<int>> candidates;
            for (int i = 0; i < nums.size(); i ++) {
                vector<int> tmp;
                for (int j = 0; j < candidates.size(); j ++) {
                    if (nums[i] % *prev(candidates[j].end()) == 0) {
                        tmp = tmp.size() > candidates[j].size() ? tmp : candidates[j];
                    }
                }
                tmp.push_back(nums[i]);
                candidates.push_back(tmp);
            }
            for (int i = 0; i < candidates.size(); i ++) {
                result = result.size() > candidates[i].size() ? result : candidates[i];
            }
            return result;
        }
    };

Log in to reply
 

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