LeetCode 17. 電話號碼的字母組合 Letter Combinations of a Phone Number
阿新 • • 發佈:2018-11-12
8-1 樹形問題 Letter Combinations of a Phone Number
題目: LeetCode 17. 電話號碼的字母組合
給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。
給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。
示例:
輸入:“23”
輸出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
說明:
儘管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。
import java.util.List;
import java.util.ArrayList;
/// 17. Letter Combinations of a Phone Number
/// https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
/// 時間複雜度: O(2^len(s))
/// 空間複雜度: O(len(s))
class Solution {
private String letterMap[] = {
" ", //0
"", //1
"abc" , //2
"def", //3
"ghi", //4
"jkl", //5
"mno", //6
"pqrs", //7
"tuv", //8
"wxyz" //9
};
private ArrayList<String> res;
public List<String> letterCombinations(String digits) {
res = new ArrayList<String>();
if(digits.equals(""))
return res;
findCombination(digits, 0, "");
return res;
}
// s中儲存了此時從digits[0...index-1]翻譯得到的一個字母字串
// 尋找和digits[index]匹配的字母, 獲得digits[0...index]翻譯得到的解
private void findCombination(String digits, int index, String s){
System.out.println(index + " : " + s);
if(index == digits.length()){
res.add(s);
System.out.println("get " + s + " , return");
return;
}
Character c = digits.charAt(index);
assert c.compareTo('0') >= 0 &&
c.compareTo('9') <= 0 &&
c.compareTo('1') != 0;
String letters = letterMap[c - '0'];
for(int i = 0 ; i < letters.length() ; i ++){
System.out.println("digits[" + index + "] = " + c +
" , use " + letters.charAt(i));
findCombination(digits, index+1, s + letters.charAt(i));
}
System.out.println("digits[" + index + "] = " + c + " complete, return");
return;
}
private static void printList(List<String> list){
for(String s: list)
System.out.println(s);
}
public static void main(String[] args) {
printList((new Solution()).letterCombinations("234"));
}
}