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
Note:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
Ideas of solving problems
Because of the small amount of data, the problem is solved by backtracking directly and using a map.Optimization: tiles can be sorted so that if they are the same as the previous one, they do not need to traverse the current one. The time complexity is O(n^2), and the space complexity is O(1). The memory consumption is 6.5Mb.
Code
package main
import (
"fmt"
)
func main(){
title := "AAB"
fmt.Println(numTilePossibilities(title))
}
func numTilePossibilities(tiles string) int {
used := make([]bool, len(tiles))
m := make(map[string]struct{})
backtrack("", used, tiles, m)
return len(m)
}
func backtrack(now string, used []bool, str string, m map[string]struct{}) {
if len(now) > 0 {
m[now] = struct{}{}
}
if len(now) == len(str) {
return
}
for i := 0; i < len(str); i++ {
if used[i] {
continue
}
used[i] = true
backtrack(now + string(str[i]), used, str, m)
used[i] = false
}
}
链接:https://leetcode-cn.com/problems/letter-tile-possibilities/solution/golang-36ms-bao-li-hui-su-by-resara/
来源:力扣(LeetCode)