# Letter Tile Possibilities in Python

PythonServer Side ProgrammingProgramming

Suppose we have a set of tiles, where each tile has one letter tiles[i] printed on it. Find the number of possible non-empty sequences of letters that we can make. So if the input is “AAB”, then the output will be 8. As sequences are “A”, “B”, “AA”, “AB”, “BA”, “AAB”, “ABA”, “BAA”

To solve this, we will follow these steps −

• Define one dfs(), that will take count
• sum := 0
• for i in range 1 to 26
• if count[i] = 0, then go for next iteration, without checking the rest
• decrease count[i] by 1, and increase sum by 1
• sum := sum + dfs(count)
• increase count[i] by 1
• return sum
• the actual method will be like −
• make one count array of size 26, and fill this with 0
• for each element i in tiles
• increase count[i – ‘A’ + 1] by 1
• return dfs(count)

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution(object):
def numTilePossibilities(self, tiles):
count = [0 for i in range(27)]
for i in tiles:
count[ord(i)-ord('A')+1]+=1
return self.dfs(count)
def dfs(self,count):
summ = 0
for i in range(1,27):
if count[i]==0:
continue
count[i]-=1
summ+=1
summ+=self.dfs(count)
count[i]+=1
return summ
ob = Solution()
print(ob.numTilePossibilities("AAB"))

## Input

"AAB"

## Output

8
Published on 30-Apr-2020 12:21:47