`

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.

用一个字符串数组模拟键盘上数字代表的字符串,用回溯法,分别记录每个可能的答案。
代码如下:
public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<String>();
        if(digits == null || digits.length() == 0) return list;
        String[] str = {"","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        getLetter(digits, str, 0, "", list);
        return list;
    }
    
    public void getLetter(String digits, String[] str, int start, String s, List<String> list) {
        if(s.length() == digits.length()) {
            list.add(s);
        }
        if(start < digits.length())
        for(int i = 0; i < str[digits.charAt(start) - '0'].length(); i++) {
            getLetter(digits, str, start + 1, s + str[digits.charAt(start) - '0'].charAt(i), list);
        }
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics