Skip to content

Commit d1c8d54

Browse files
committed
Sync LeetCode submission Runtime - 58 ms (25.91%), Memory - 17.7 MB (96.09%)
1 parent 36b83cf commit d1c8d54

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<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>
2+
3+
<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>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> tiles = &quot;AAB&quot;
10+
<strong>Output:</strong> 8
11+
<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;.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> tiles = &quot;AAABBC&quot;
18+
<strong>Output:</strong> 188
19+
</pre>
20+
21+
<p><strong class="example">Example 3:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> tiles = &quot;V&quot;
25+
<strong>Output:</strong> 1
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= tiles.length &lt;= 7</code></li>
33+
<li><code>tiles</code> consists of uppercase English letters.</li>
34+
</ul>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Approach 2: Optimized Recursion
2+
3+
# Time: O(2^n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def numTilePossibilities(self, tiles: str) -> int:
8+
char_count = [0] * 26
9+
for char in tiles:
10+
char_count[ord(char) - ord('A')] += 1
11+
12+
return self._find_sequences(char_count)
13+
14+
def _find_sequences(self, char_count):
15+
total = 0
16+
17+
for pos in range(26):
18+
if char_count[pos] == 0:
19+
continue
20+
21+
# Add current char and recurse
22+
total += 1
23+
char_count[pos] -= 1
24+
total += self._find_sequences(char_count)
25+
char_count[pos] += 1
26+
27+
return total
28+

0 commit comments

Comments
 (0)