leetcode Letter Combinations of a Phone Number题解

题目描述:

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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.

中文理解:

给定由2-9组成的字符串,给出所有可能的字符组合,2-9每个数字对应的字符集合如图中所示。

解题思路:

使用递归的思路,第一个数字对应的几个字符分别递归到下一个字符,得到所有不同的组合。

扫描二维码关注公众号,回复: 6187389 查看本文章

代码(java):

class Solution {
    List res;
    StringBuilder sb;
    public List<String> letterCombinations(String digits) {
        res=new ArrayList();
        if(digits.length()==0)return res;
        String []map={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        String []digitsText=new String[digits.length()];
        for(int i=0;i<digits.length();i++){
            digitsText[i]=map[digits.charAt(i)-'0'-2];
        }
        sb=new StringBuilder();
        recursion(digitsText,sb);
        return res;
    }
    public void recursion(String []digitsText,StringBuilder sb){
        if(sb.length()==digitsText.length){
            res.add(sb.toString());
            return;
        }
        int row=sb.length();
        for(int i=0;i<digitsText[row].length();i++){
            sb.append(digitsText[row].charAt(i));
            recursion(digitsText,sb);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/89945728