Letter Tile Possibilities Problem
Description
LeetCode Problem 1079.
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7tilesconsists of uppercase English letters.
Solution
Approach: Backtracking on Letter Counts
Permuting the tile positions would count the same sequence many times when letters repeat ("AAB" has two A tiles, but "AB" is only one sequence). Instead, count how many tiles of each letter we have and build sequences one letter at a time, choosing a letter, not a tile.
dfs() returns the number of non-empty sequences we can still build from the remaining tiles. For every letter that still has a tile:
- Using it gives one new sequence that ends here, so add
1. - Take one tile of that letter away, add
dfs()for all longer sequences that continue after it, then put the tile back.
Since each step picks a distinct letter, two different paths of choices always give different sequences, and no sequence is counted twice. The answer is dfs() on the full counts.
Complexity: O(26 · S) time, where S is the number of distinct sequences (at most 13,699 for 7 distinct tiles): each sequence is one call, and each call loops over 26 letters. O(n) recursion depth, where n is the number of tiles.
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
cnt = [0] * 26
for c in tiles:
cnt[ord(c) - ord("A")] += 1
def dfs() -> int:
# Number of non-empty sequences we can still build from the remaining tiles.
res = 0
for i in range(26):
if cnt[i] > 0:
res += 1 # the sequence that ends with letter i here
cnt[i] -= 1
res += dfs() # the longer ones that continue after it
cnt[i] += 1
return res
return dfs()