<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p>

<ul>
	<li><code>answer[i] % answer[j] == 0</code>, or</li>
	<li><code>answer[j] % answer[i] == 0</code></li>
</ul>

<p>If there are multiple solutions, return any of them.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> [1,3] is also accepted.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,4,8]
<strong>Output:</strong> [1,2,4,8]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li>
	<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>
</ul>

class Solution {
public:
    vector<int> comp(vector<int> &a, vector<int> b){
        if(a.size() > b.size()) return a;
        return b;
    }
    // unordered_map<string,vector<int>> dp;
    // vector<int> solve(vector<int> &nums, int i, int prev){
    //     if(i==nums.size()) return {};
    //     // string key = to_string(i)+"#"+to_string(prev);
    //     // if(dp.find(key)!=dp.end()) return dp[key];
    //     vector<int> ans;
    //     if(prev==-1){
    //         ans=solve(nums,i+1,i);
    //         ans.push_back(nums[i]);
    //     }else{
    //         if(nums[i]%nums[prev]==0){
    //             ans=solve(nums,i+1,i);
    //             ans.push_back(nums[i]);
    //         }
                
    //     }
    //     ans=comp(ans,solve(nums,i+1,prev));
    //     return ans;
    // }
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        // unordered_map<string,vector<int>> dp;
        // return solve(nums,0,-1);
        int n = nums.size();
        vector<vector<int>> dp(n);
        for(int i=0;i<n;i++){
            dp[i]={nums[i]};
        }
        vector<int> ans;
        for(int i=0;i<n;i++){
            for(int j=0;j<i;j++){
                if(nums[i]%nums[j]==0){
                    if(dp[j].size()+1>dp[i].size()){
                        dp[i]=dp[j];
                        dp[i].push_back(nums[i]);
                    }
                }
            }
            ans=comp(ans,dp[i]);
        }
        return ans;
    }
};
15800