Letter Tile Possibilities

  23 Jun 2019

By Wen Xu

leetcode algorithm recursion

Problem description

You have a set of 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.

Example 1:

Input: “AAB” Output: 8 Explanation: The possible sequences are “A”, “B”, “AA”, “AB”, “BA”, “AAB”, “ABA”, “BAA”. Example 2:

Input: “AAABBC” Output: 188

Solution

Here I used recursion to solve the problem. The code is self explainatory.

class Solution:
    def numTilePossibilities(self, tiles: str) -> int:
        
        
        def tileset(tiles:str)-> set:
            if len(tiles) == 0:
                return set([""])
            t = set([])
            s = tileset(tiles[1:])
            for item in s:   
                for i in range(len(item) + 1):
                    t.add(item[:i] + tiles[0] + item[i:])
            t.update(s)
            return t
        
        return len(tileset(tiles)) - 1
        
comments powered by Disqus