<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> largestDivisibleSubset(vector<int>& nums) {
        //memo[i] = max(memo[i - 1], # elements with nums[i] modding over all nums[0] to nums[i-1])
        sort(nums.begin(), nums.end());
        vector<vector<int>> memo(nums.size());
        for(int i = 0; i < nums.size(); ++i) memo[i] = {nums[i]};
        for(int i = nums.size() - 2; i >= 0; --i){
            vector<int> curr_nums = memo[i];
            int curr_max = 0;
            for(int j = i + 1; j < nums.size(); ++j){
                if(memo[j].size() > curr_max && nums[j] % nums[i] == 0){
                    curr_max = memo[j].size();
                    curr_nums = memo[i];
                    for (int element : memo[j]) curr_nums.push_back(element);
                } 
            }
            memo[i] = curr_nums;
        }
        int max_size = 0;
        vector<int> result;
        for(auto mem : memo){
            if(mem.size() > max_size){
                result = mem;
                max_size = mem.size();
            }
        }
        return result;

    }
};
14800