<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:
    int numTilePossibilities(string tiles) {
        
        std::map<int,int> letterCount{};
        for(char c: tiles)
        {
            letterCount[c-'A']++;
        }
        
        int total{};
        
        for(int size=1; size<=tiles.size(); size++)
        {
           total+= numPossibleStrings(letterCount, size, 0);
        }
        
        return total;
        
    }
    
private:
    int numPossibleStrings(std::map<int,int>& count, int size, int firstLetter)
    {
        //a substring can contain between 0 and min(size, count(l)) number of times the letter l
        //we place them using (size choose #occurences) possible places
        
        if(firstLetter >= 26)
        {
            return 0;
        }
        
        if(size==0)
        {
            return 1;
        }
        
        if(size==1)
        {
            int total = numPossibleStrings(count, 1,firstLetter+1);
            if(count[firstLetter]>0)
            {
                total++;
            }
            return total;
        }
        
        int nbStrings{};
        
        for(int i=0; i<= std::min(count[firstLetter],size); i++)
        {
            //we have i occurences of the first letter
            nbStrings += numPossibleStrings(count, size-i, firstLetter+1)*nChooseK(size,i);
            
        }
        
        return nbStrings;
    }
    
    int nChooseK(int n, int k)
    {
        if(n==0 )
        {
            return 0;
        }
        
        if(k==0)
        {
            return 1;
        }
        
        int kFactorial=1;
        int numerator=1;
        
        for(int i=0; i<k; i++)
        {
            kFactorial*= i+1;
            numerator*= (n-i);
        }
        
        return (numerator/kFactorial);
        
    }
};
9864