The Letter Tile Possibilities problem involves finding all possible sequences of letters that can be formed using the given tiles. Each tile can be used only once per sequence, and the order of tiles matters.
class Solution {
public int numTilePossibilities(String tiles) {
char[] chars = tiles.toCharArray();
Arrays.sort(chars); // Sort to handle duplicates
boolean[] visited = new boolean[chars.length];
return backtrack(chars, visited);
}
private int backtrack(char[] chars, boolean[] visited) {
int count = 0;
for (int i = 0; i < chars.length; i++) {
if (visited[i] || (i > 0 && chars[i] == chars[i - 1] && !visited[i - 1])) {
continue; // Skip duplicates
}
visited[i] = true;
count += 1 + backtrack(chars, visited); // Count current sequence and recurse
visited[i] = false; // Backtrack
}
return count;
}
}
O(n!)
, where n
is the number of tiles. This accounts for all permutations of the tiles.O(n)
, for the recursion stack and visited array.Input: tiles = "AAB"
Output: 8
Explanation:
The possible sequences are:
"A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
visited
array to track which tiles have been used in the current sequence.