给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

Leetcode--17.电话号码的字母组合

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:

回溯法

提交的代码:

class Solution {

    Map<String, String> phone = new HashMap<String, String>() {{

    put("2", "abc");

    put("3", "def");

    put("4", "ghi");

    put("5", "jkl");

    put("6", "mno");

    put("7", "pqrs");

    put("8", "tuv");

    put("9", "wxyz");

  }};

    List<String> output = new ArrayList<String>();

    public List<String> letterCombinations(String digits) {

        if(digits.length()!=0)

        {

            back("",digits);

        }

        return output;

    }

    public void back(String now,String next_word)

    {

        if(next_word.length()==0)

        {

            output.add(now);

        }

        else

        {

            String y = next_word.substring(0,1);//获得当前数字

            String x = phone.get(y);  //获得每个数字代表的字母

            for(int i=0;i<x.length();i++)

            {

                String z = x.substring(i,i+1);

                back(now.concat(z),next_word.substring(1));

            }

        }

    }

}

相关文章: