Solution of Letter Tile Possibilities

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值