<p>You have <code>n</code>&nbsp;&nbsp;<code>tiles</code>, where each tile has one letter <code>tiles[i]</code> printed on it.</p>

<p>Return <em>the number of possible non-empty sequences of letters</em> you can make using the letters printed on those <code>tiles</code>.</p>

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

<pre>
<strong>Input:</strong> tiles = &quot;AAB&quot;
<strong>Output:</strong> 8
<strong>Explanation: </strong>The possible sequences are &quot;A&quot;, &quot;B&quot;, &quot;AA&quot;, &quot;AB&quot;, &quot;BA&quot;, &quot;AAB&quot;, &quot;ABA&quot;, &quot;BAA&quot;.
</pre>

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

<pre>
<strong>Input:</strong> tiles = &quot;AAABBC&quot;
<strong>Output:</strong> 188
</pre>

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

<pre>
<strong>Input:</strong> tiles = &quot;V&quot;
<strong>Output:</strong> 1
</pre>

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

<ul>
	<li><code>1 &lt;= tiles.length &lt;= 7</code></li>
	<li><code>tiles</code> consists of uppercase English letters.</li>
</ul>

class Solution {
public:
    void backtrack(string& tiles, size_t i, set<string>& out) {
        if (i >= tiles.size()) {
            //cout << tiles << endl;
            out.insert(tiles.substr(0, i));
            return;
        }

        backtrack(tiles, i+1, out);
        for (size_t j = i+1; j < tiles.size(); j++) {
            swap(tiles[i], tiles[j]);
            backtrack(tiles, i+1, out);
            swap(tiles[i], tiles[j]);
        }
    }

    int numTilePossibilities2(string tiles) {
        // sort(tiles.begin(), tiles.end());
        set<string> out;
        backtrack(tiles, 0, out);
        return out.size();
    }

    int countPerm(const string& s) {
        const int perms[] = {1, 1, 2, 6, 24, 120, 720, 5040};
        int perm = perms[s.size()];
        int freqs[26] = {0};
        for (auto c: s) freqs[c-'A']++;
        for (auto f: freqs) if (f > 0) perm /= perms[f];
        return perm;
    }
    int dfs(const string& tiles, const string& tmp, size_t i, set<string>& unique) {
        if (i >= tiles.size()) {
            //cout << tiles << endl;
            return unique.insert(tmp).second ? countPerm(tmp) : 0;
        }

        return dfs(tiles, tmp, i+1, unique) + dfs(tiles, tmp+tiles[i], i+1, unique);
    }
    int numTilePossibilities(string tiles) {
        sort(tiles.begin(), tiles.end());
        set<string> unique;
        return dfs(tiles, "", 0, unique) - 1;
    }
};
10118