<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:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        '''
            sort so we only need to care about 1 direction
            1,2,4 8
            a2 % a1 = 0 and a3 % a2 = 0 => a3 % a1 will also = 0
            hence only need to care about the previously picked number

            dp array: dp[i][j] = largest subset starting at i given the previously picked num was j
        '''
        nums.sort()
        # memo = {}
        # def dp(idx, prev):
        #     if idx >= len(nums):
        #         return []
        #     elif (idx, prev) in memo:
        #         return memo[(idx, prev)]
        #     else:
        #         skip = dp(idx+1, prev)
        #         take = []
        #         if prev is None or nums[idx] % nums[prev] == 0:                    
        #             take = [nums[idx]] + dp(idx+1, idx)

        #         if len(skip) > len(take):
        #             memo[(idx, prev)] = skip
        #         else:
        #             memo[(idx, prev)] = take

        #         return memo[(idx, prev)]
        dp = [[[] for _ in range(len(nums)+1)] for _ in range(len(nums)+1)]

        for i in range(len(nums)-1, -1, -1):
            for j in range(i):
                skip = dp[i+1][j]
                take = []
                if nums[i] % nums[j] == 0:
                    take = [nums[i]] + dp[i+1][i]
                if len(skip) > len(take):
                    dp[i][j] = skip
                else:
                    dp[i][j] = take
            skipNoPrev = dp[i+1][-1]
            takeNoPrev = [nums[i]] + dp[i+1][i]
            if len(skipNoPrev) > len(takeNoPrev):
                dp[i][-1] = skipNoPrev
            else:
                dp[i][-1] = takeNoPrev
            
            

        return dp[0][-1]
42948