<p>Given a string <code>num</code> that contains only digits and an integer <code>target</code>, return <em><strong>all possibilities</strong> to insert the binary operators </em><code>&#39;+&#39;</code><em>, </em><code>&#39;-&#39;</code><em>, and/or </em><code>&#39;*&#39;</code><em> between the digits of </em><code>num</code><em> so that the resultant expression evaluates to the </em><code>target</code><em> value</em>.</p>

<p>Note that operands in the returned expressions <strong>should not</strong> contain leading zeros.</p>

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

<pre>
<strong>Input:</strong> num = &quot;123&quot;, target = 6
<strong>Output:</strong> [&quot;1*2*3&quot;,&quot;1+2+3&quot;]
<strong>Explanation:</strong> Both &quot;1*2*3&quot; and &quot;1+2+3&quot; evaluate to 6.
</pre>

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

<pre>
<strong>Input:</strong> num = &quot;232&quot;, target = 8
<strong>Output:</strong> [&quot;2*3+2&quot;,&quot;2+3*2&quot;]
<strong>Explanation:</strong> Both &quot;2*3+2&quot; and &quot;2+3*2&quot; evaluate to 8.
</pre>

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

<pre>
<strong>Input:</strong> num = &quot;3456237490&quot;, target = 9191
<strong>Output:</strong> []
<strong>Explanation:</strong> There are no expressions that can be created from &quot;3456237490&quot; to evaluate to 9191.
</pre>

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

<ul>
	<li><code>1 &lt;= num.length &lt;= 10</code></li>
	<li><code>num</code> consists of only digits.</li>
	<li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution:
    def addOperators(self, num: str, target: int) -> List[str]:
        """
        - DFS (backtracking)
        - We have three choices for operations of every idx: +, -, and *
            - Recurse into each path, storing the current path of ops and values.
            - Store paths in a set--we shouldn't have duplicates but why not.
        - Also note that the answer doesn't _have_ to interleave an operator. e.g. 105 -> 10 - 5
        - Multiplication is not commutative
            - Generate the full path, then execute it and test against target.
            - If the operation produces a value > target, abandon it.
            - If the operation produces a value < target and there are no more values to consume, abandon it.
            - Win condition: chars interleaved with ops == target.
        """

        ops = {
            '+': add,
            '-': sub,
            '*': mul,
        }

        paths = set()
        def dfs(idx: int, path: List[str]) -> None:
            if idx >= len(num):
                paths.add("".join(path))
                return

            next_val = num[idx]
            if idx == 0:
                dfs(idx + 1, path + f"{next_val}")
                return

            dfs(idx + 1, path + f"{next_val}")

            for name, op in ops.items():
                dfs(idx + 1, path + f"{name}{next_val}")

        dfs(0, "")

        """
        For each path in paths, parse and evaluate.
        - Need to get each full number
            - Store last_num_str until we see an operator.
                - Perform usual operator logic on the prev if we do
            - If num starts with "0", throw the path out
        - Store the last seen operator. If op is none or '+', push val to list to add.
        - If last op is '-', push -val to list
        - If last op is '*', pop from end of list, multiply, and put result back in list.
        """
        res = []
        for path in paths:
            to_sum = []
            last_op = None
            last_num = ""
            for char in path:

                if char.isnumeric():
                    last_num += char
                    continue

                # Leading 0s are invalid
                if len(last_num) > 1 and last_num.startswith("0"):
                    break

                val = int(last_num)
                last_num = ""
                if last_op == '*':
                    to_sum.append(val * to_sum.pop()) 
                elif last_op == '-':
                    to_sum.append(-val)
                else:
                    # Last op is + or None
                    to_sum.append(val)

                last_op = char

            if len(last_num) > 1 and last_num.startswith("0"):
                continue

            val = int(last_num)
            last_num = ""
            if last_op == '*':
                to_sum.append(val * to_sum.pop())
            elif last_op == '-':
                to_sum.append(-val)
            else:
                # Last op is + or None
                to_sum.append(val)

            if sum(to_sum) == target: 
                res.append(path)

        return res
156000