Letter Tile Possibilities

medium backtracking counting dfs

Problem

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 using the letters printed on those tiles.

Inputtiles = "AAB"
Output8
The sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

def num_tile_possibilities(tiles):
    count = [0] * 26
    for c in tiles:
        count[ord(c) - ord('A')] += 1

    def dfs():
        total = 0
        for i in range(26):
            if count[i] > 0:
                total += 1          # use this tile as next letter
                count[i] -= 1
                total += dfs()      # extend the sequence
                count[i] += 1       # backtrack
        return total

    return dfs()
function numTilePossibilities(tiles) {
  const count = new Array(26).fill(0);
  for (const c of tiles) count[c.charCodeAt(0) - 65]++;

  function dfs() {
    let total = 0;
    for (let i = 0; i < 26; i++) {
      if (count[i] > 0) {
        total += 1;          // use this tile as next letter
        count[i]--;
        total += dfs();      // extend the sequence
        count[i]++;          // backtrack
      }
    }
    return total;
  }

  return dfs();
}
class Solution {
    int[] count = new int[26];

    public int numTilePossibilities(String tiles) {
        for (char c : tiles.toCharArray()) count[c - 'A']++;
        return dfs();
    }

    private int dfs() {
        int total = 0;
        for (int i = 0; i < 26; i++) {
            if (count[i] > 0) {
                total += 1;          // use this tile as next letter
                count[i]--;
                total += dfs();      // extend the sequence
                count[i]++;          // backtrack
            }
        }
        return total;
    }
}
class Solution {
public:
    int count[26] = {0};

    int numTilePossibilities(string tiles) {
        for (char c : tiles) count[c - 'A']++;
        return dfs();
    }

    int dfs() {
        int total = 0;
        for (int i = 0; i < 26; i++) {
            if (count[i] > 0) {
                total += 1;          // use this tile as next letter
                count[i]--;
                total += dfs();      // extend the sequence
                count[i]++;          // backtrack
            }
        }
        return total;
    }
};
Time: O(n · n!) Space: O(n)