Java [leetcode 17]Letter Combinations of a Phone Number

题目描述:

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"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

解题思路:

递归法解题之。从第一个字符串开始确认结果,然后递归地确认余下各项结果。

参考博客:http://blog.csdn.net/china_wanglong/article/details/38495355

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        String[] map = new String[] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        char[] tmp = new char[digits.length()];
        if(digits.length() == 0)
            return result;
        rec(digits, 0, tmp, map, result);
        return result;
    }
    public void rec(String digits, int index, char[] tmp, String[] map, List<String> result){
        if(index == digits.length()){
            result.add(new String(tmp));
            return;
        }
        char tmpChar = digits.charAt(index);
        for(int i = 0; i < map[tmpChar - '0'].length(); i++){
            tmp[index] = map[tmpChar - '0'].charAt(i);
            rec(digits, index + 1, tmp, map, result);
        }
    }
}

 

posted @   scottwang  阅读(1205)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示