美文网首页
LeetCode|Letter Combinations of

LeetCode|Letter Combinations of

作者: lycknight | 来源:发表于2016-10-20 09:59 被阅读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"].

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

思路:可以使用递归的方式来解决此题。

public List<String> letterCombinations(String digits) {
        List<String> rec = new ArrayList<String>();
        if (digits == null || digits.length() == 0) {
            return rec;
        }

        String[] letters = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder string = new StringBuilder();

        lettersCombinations(digits, letters, 0, rec, string);
        return rec;
    }

public void lettersCombinations(String digits, String[] letters, int number, List<String> rec, StringBuilder string) {
        if (digits.length() == number) {
            rec.add(string.toString());
            return;
        }

        String letter = letters[digits.charAt(number) - '2'];

        for (int i = 0; i < letter.length(); i++) {
            string.append(letter.charAt(i));
            lettersCombinations(digits, letters, number + 1, rec, string);
            string.deleteCharAt(string.length() - 1);
        }

    }

相关文章

网友评论

      本文标题:LeetCode|Letter Combinations of

      本文链接:https://www.haomeiwen.com/subject/ahdfuttx.html