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
.
For example:
tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
tiles = "AAABBC"
Output: 188
tiles = "V"
Output: 1
from collections import Counter
def numTilePossibilities(tiles: str) -> int:
count = Counter(tiles)
result = set()
def backtrack(combination):
if combination:
result.add(combination)
for char in count:
if count[char] > 0:
count[char] -= 1
backtrack(combination + char)
count[char] += 1
backtrack("")
return len(result)
Initialization:
Counter
to count the occurrences of each tile.result
is a set to store unique sequences.Backtracking Function:
backtrack
function generates sequences recursively.combination
string as input, representing the current sequence.combination
is not empty, it's added to the result
set.char
) in the count
:
char
is greater than 0:
char
.backtrack
with the updated combination
(adding char
to it).char
to backtrack and explore other possibilities.Main Logic:
backtrack
function with an empty string to start generating sequences.result
set, which contains all unique non-empty sequences.Let's trace the execution with tiles = "AAB"
:
count = {"A": 2, "B": 1}
backtrack("")
:
char = "A"
: count["A"] = 1
, backtrack("A")
result.add("A")
char = "A"
: count["A"] = 0
, backtrack("AA")
result.add("AA")
char = "B"
: count["B"] = 1
, backtrack("AAB")
result.add("AAB")
backtrack("AAB")
returnscount["B"] = 0
backtrack("AA")
returnscount["A"] = 1
char = "B"
: count["B"] = 0
, backtrack("AB")
result.add("AB")
char = "A"
: count["A"] = 1
, backtrack("ABA")
result.add("ABA")
backtrack("ABA")
returnscount["A"] = 0
backtrack("AB")
returnscount["B"] = 1
backtrack("A")
returnscount["A"] = 2
char = "B"
: count["B"] = 0
, backtrack("B")
result.add("B")
char = "A"
: count["A"] = 1
, backtrack("BA")
result.add("BA")
char = "A"
: count["A"] = 0
, backtrack("BAA")
result.add("BAA")
backtrack("BAA")
returnscount["A"] = 1
backtrack("BA")
returnscount["A"] = 2
backtrack("B")
returnscount["B"] = 1
backtrack("")
returnsreturn len(result)
which is 8.
result
set and the call stack during recursion. In the worst case, this space can grow significantly with the length of the input string, as the number of possible sequences increases factorially.