欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

17. 电话号码的字母组合

程序员文章站 2022-04-16 23:53:50
...

文章目录

题干

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

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
17. 电话号码的字母组合
示例:

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

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

题解

很显然,这是一个全排列问题,而且这个问题不需要剪枝,使用回溯算法。

class Solution {
    String[] phone = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    List<String> output = new ArrayList<String>();
    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0)
            return output;
        backtrack("", digits);
        return output;
    }
    public void backtrack(String combination, String next_digits) {
        if(next_digits.length() == 0)
        {
            output.add(combination);
            return;
        }
        String digit = next_digits.substring(0, 1);//取第一个字符
        String letters = phone[Integer.parseInt(digit)];//digit对应的三个字母
        for(int i = 0; i < letters.length(); i++)//遍历三/四个字母
        {
            String letter = letters.substring(i,i +1 );
            backtrack(combination + letter, next_digits.substring(1));
        }
    }
}
相关标签: LeetCode