关闭

Middle-题目72:17. Letter Combinations of a Phone Number

74人阅读 评论(0) 收藏 举报
分类:

题目原文:
Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.
这里写图片描述
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
题目大意:
给出一个九键键盘,和数字序列,求出所有可能的对应字母组合。
题目分析:
还是一个暴力的回溯法,使用backtrack(List list, String digits, String currentLetter, int index)维护搜索过程,其中list是字母组合的列表,digits是数字序列,currentLetter是当前的搜索结果,index记录digits串中该搜索的位置。
源码:(language:java)

public class Solution {
    private String[][] letters = new String[][] {
        {" "},
        {},
        {"a","b","c"},
        {"d","e","f"},
        {"g","h","i"},
        {"j","k","l"},
        {"m","n","o"},
        {"p","q","r","s"},
        {"t","u","v"},
        {"w","x","y","z"}
    };
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<String>();
        if(digits.length() > 0)
            backtrack(list, digits, new String(), 0);
        return list;
    }
    private void backtrack(List<String> list, String digits, String currentLetter, int index) {
        if(index == digits.length()) {
            list.add(currentLetter);
            return;
        }
        else {
            int num = digits.charAt(index) -'0';
            for(int i = 0; i < letters[num].length; i++) {
                currentLetter+=letters[num][i];
                backtrack(list, digits, currentLetter, index+1);
                currentLetter = currentLetter.substring(0,currentLetter.length()-1);
            }
        }
    }
}

成绩:
1ms,beats 46.02%,众数1ms,53.98%

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:56041次
    • 积分:3202
    • 等级:
    • 排名:第10679名
    • 原创:270篇
    • 转载:53篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论