Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

17. 电话号码的字母组合 #59

Open
yankewei opened this issue Sep 15, 2020 · 1 comment
Open

17. 电话号码的字母组合 #59

yankewei opened this issue Sep 15, 2020 · 1 comment
Labels
中等 题目难度为中等 回溯算法 题目包含回溯算法解法 字符串 题目类型为字符串

Comments

@yankewei
Copy link
Owner

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

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

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

说明:

尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number

@yankewei yankewei added 中等 题目难度为中等 字符串 题目类型为字符串 回溯算法 题目包含回溯算法解法 labels Sep 15, 2020
@yankewei
Copy link
Owner Author

一看这种组合全排列,就可以想到使用回溯算法。回溯算法的本质就是求出所有的可能解,遍历所有的可能答案。

var ret []string
var m = map[byte][]byte{
    '2': []byte{'a', 'b', 'c'},
    '3': []byte{'d', 'e', 'f'},
    '4': []byte{'g', 'h', 'i'},
    '5': []byte{'j', 'k', 'l'},
    '6': []byte{'m', 'n', 'o'},
    '7': []byte{'p', 'q', 'r', 's'},
    '8': []byte{'t', 'u', 'v'},
    '9': []byte{'w', 'x', 'y', 'z'},
}
func letterCombinations(digits string) []string {
    if digits == "" {
        return []string{}
    }
    ret = []string{}
    dfs(digits, 0, []byte{})
    return ret
}

func dfs(digits string, index int, promot []byte) {
    if len(digits) == len(promot) {
	ret = append(ret, string(promot))
	return
    }
    for _, v := range m[digits[index]] {
	promot = append(promot, v)
	dfs(digits, index+1, promot)
	promot = promot[:len(promot)-1]
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 回溯算法 题目包含回溯算法解法 字符串 题目类型为字符串
Projects
None yet
Development

No branches or pull requests

1 participant