給定一個僅包含數(shù)字?2-9?的字符串蛹锰,返回所有它能表示的字母組合深胳。
給出數(shù)字到字母的映射如下(與電話按鍵相同)。注意 1 不對應(yīng)任何字母铜犬。
示例:
輸入:"23"
輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
說明:
盡管上面的答案是按字典序排列的舞终,但是你可以任意選擇答案輸出的順序。
package com.tao.top_100_liked_questions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class _17_letterCombinations {
static Mapphone =new HashMap(){{
put("2","abc");
? ? ? ? put("3", "def");
? ? ? ? put("4", "ghi");
? ? ? ? put("5", "jkl");
? ? ? ? put("6", "mno");
? ? ? ? put("7", "pqrs");
? ? ? ? put("8", "tuv");
? ? ? ? put("9", "wxyz");
? ? }
};
? ? static Listoutput =new ArrayList<>();
? ? public static void main(String[] args){
letterCominations("23");
? ? }
public static ListletterCominations(String digits){
if(digits.length() !=0) {
backtrack("",digits);
? ? ? ? }
return output;
? ? }
static int count =0;
? ? public static void backtrack(String combination,String next_digits){
if(next_digits.length() ==0){
System.out.println(" res ---------: " +combination);
? ? ? ? ? ? output.add(combination);
? ? ? ? }else {
String digit = next_digits.substring(0,1);
? ? ? ? ? ? String letters =phone.get(digit);
? ? ? ? ? ? for (int i =0; i
String letter =phone.get(digit).substring(i,i+1);
? ? ? ? ? ? ? ? System.out.println("combination : " + combination+letter +", count "+(++count)
+", digit: " + digit);
? ? ? ? ? ? ? ? backtrack(combination+letter,next_digits.substring(1));
? ? ? ? ? ? }
}
}
}