<p>Given an array of digits <code>digits</code>, return <em>the largest multiple of <strong>three</strong> that can be formed by concatenating some of the given digits in <strong>any order</strong></em>. If there is no answer return an empty string.</p>

<p>Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.</p>

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

<pre>
<strong>Input:</strong> digits = [8,1,9]
<strong>Output:</strong> &quot;981&quot;
</pre>

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

<pre>
<strong>Input:</strong> digits = [8,6,7,1,0]
<strong>Output:</strong> &quot;8760&quot;
</pre>

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

<pre>
<strong>Input:</strong> digits = [1]
<strong>Output:</strong> &quot;&quot;
</pre>

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

<ul>
	<li><code>1 &lt;= digits.length &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= digits[i] &lt;= 9</code></li>
</ul>

class Solution
{
public:

    int dfs(int i, int sum, std::vector<int> &digits)
    {
        auto n = digits.size();
        if (i == n)
        {
            return sum == 0 ? 0 : INT_MIN;
        }

        if (m_memo[0][i][sum] != INT_MIN)
        {
            return m_memo[0][i][sum];
        }

        // include i
        auto with = 1 + dfs(i + 1, (sum + digits[i]) % 3, digits);

        // don't include i
        auto without = dfs(i + 1, sum % 3, digits);

        if (with < without)
        {
            m_memo[1][i][sum] = 1;
        }
        else
        {
            m_memo[1][i][sum] = 2;
        }
        return m_memo[0][i][sum] = std::max(with, without);
    }

    std::string largestMultipleOfThree(std::vector<int> &digits)
    {
        std::sort(std::begin(digits), std::end(digits), std::greater<int>());
        auto n = digits.size();
        m_memo[0].resize(n + 1, std::vector<int>(3, INT_MIN));
        m_memo[1].resize(n + 1, std::vector<int>(3, 0));
        int max = dfs(0, 0, digits);
        string answer;
        int i = 0;
        int j = 0;
        while (i < n)
        {
            if(m_memo[1][i][j] == 2)
            {
                answer.push_back('0' + digits[i]);
                j = (j + digits[i]) % 3;
                i++;
            }
            else
            {
                ++i;
            }
        }

        if(answer[0]=='0'){
            return "0";
        }
        return answer;
    }
    std::vector<std::vector<int>> m_memo[2];
};
36820