描述
給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。
給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。
示例:
輸入:“23”
輸出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
說明:
儘管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。
解題思路
回溯法
- 先保存所有的數字對應的字母,用一個map容器phone保存
- 逐一取每個數字串的第一個數字,去除phone中數字對應的字母,逐一遍歷數字對應的字母,加字母加入結果集,再對剩餘的數字與字母重複操作,如:
Java代碼示例
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @lc app=leetcode.cn id=17 lang=java
*
* [17] 電話號碼的字母組合
*/
// @lc code=start
class Solution {
Map<String,String>phone = new HashMap<String,String>(){
/**
*
*/
private static final long serialVersionUID = 1L;
{
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>result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits.length()!=0){
backTrack("",digits);
}
return result;
}
public void backTrack(String combination,String next_digits){
if(next_digits.length()==0){
result.add(combination);
}else{
String digit = next_digits.substring(0, 1);
String charSet = phone.get(digit);
for(int i=0;i<charSet.length();i++){
String letter = charSet.substring(i, i+1);
backTrack(combination+letter, next_digits.substring(1));
}
}
}
}
// @lc code=end