Share my 68ms solution


  • 0
    C
    class Solution {
    public:
        vector<int> largestDivisibleSubset(vector<int>& nums) {
            sort(nums.begin(),nums.end());
            vector<int> dp(nums.size(),0),idx(nums.size(),0),ret;
            if(nums.size()==0) return ret;
            int start,longest = 0;
            for(int i=nums.size()-1;i>=0;i--){
                int M = -1;
                for(int j=i;j<nums.size();j++){
                    if(nums[j]%nums[i]==0&&dp[j]>M){
    					M = dp[j];
                        dp[i] = dp[j]+1;
                        idx[i] = j;
                    }
                }
                start = dp[i]>longest?i:start;
    			longest = longest>dp[i]?longest:dp[i];
            }
            while(idx[start]!=start){
                ret.push_back(nums[start]);
                start = idx[start];
            }
    		ret.push_back(nums[start]);
            return ret;
        }
    };

Log in to reply
 

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