<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:

    void util (vector<int> &nums, int idx, vector<int> &current, vector<int> &largest) {
        if (idx == nums.size()) {
            if (largest.size() < current.size()) {
                largest = current;
            }
            return;
        }

        util (nums, idx+1, current, largest);
        if (current.size() == 0 || nums[idx] % current.back() == 0) {
            current.push_back(nums[idx]);
            util(nums, idx+1, current, largest);
            current.pop_back();
        }
    }

    vector<int> largestDivisibleSubsetRecursive(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        vector<int> largest, current;
        util (nums, 0, current, largest);
        return largest;

    }

    vector<int> largestDivisibleSubset(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();

        vector<vector<int>> dp;
        for (int i = 0; i < n; ++i) {
            dp.push_back(vector<int> (1, nums[i]));
        }
        vector<int> largest = dp[0];

        for (int i = 1; i < n; ++i) {
            int currentLargestIdx = -1;
            for (int j = i-1; j >= 0; --j) {
                if (nums[i] % nums[j] == 0) {
                    if (currentLargestIdx == -1 || dp[currentLargestIdx].size() < dp[j].size()) {
                        currentLargestIdx = j;
                    }
                }
            }
            if (currentLargestIdx != -1) {
                dp[i] = dp[currentLargestIdx];
                dp[i].push_back(nums[i]);
            }
            if (largest.size() < dp[i].size()) {
                largest = dp[i];
            }
        }
        return largest;
    }

};
14700