NOTE

电话号码的字母组合

电话号码的字母组合:使用 DFS 枚举组合。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

2. 思路

  • 全排列

3. 实现

package main

import "sort"

var m = map[rune][]rune{
	'2': {'a', 'b', 'c'},
	'3': {'d', 'e', 'f'},
	'4': {'g', 'h', 'i'},
	'5': {'j', 'k', 'l'},
	'6': {'m', 'n', 'o'},
	'7': {'p', 'q', 'r', 's'},
	'8': {'t', 'u', 'v'},
	'9': {'w', 'x', 'y', 'z'},
}

func LetterCombinations(digits string) []string {
	if digits == "" {
		return nil

	}
	digitsPerms := make([]string, 0)
	abc := make([]rune, len(digits), len(digits))
	digitsPermutation([]rune(digits), abc, 0, &digitsPerms)
	sort.Strings(digitsPerms)
	return digitsPerms
}

func digitsPermutation(digits []rune, abc []rune, index int, digitsPerms *[]string) {
	if index == len(digits) {
		*digitsPerms = append(*digitsPerms, string(abc))
		return
	}

    //这里数字是有顺序的,所以不需要交换进行全排列
	currentNum := digits[index]
	for _, r := range m[currentNum] {
		abc[index] = r
		digitsPermutation(digits, abc, index+1, digitsPerms)
	}

}

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看