1. 程式人生 > >17. Letter Combinations of a Phone Number(根據手機按鍵求字母的組合)

17. Letter Combinations of a Phone Number(根據手機按鍵求字母的組合)

Given a digit string, 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.

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

題目大意:給定一個由數字構成的字串,根據如圖所示的手機按鍵中的 數字->字串 的關係,求出所有可能字母的組合。例如,給定數字字串 “23”,因為2在手機按鍵上對應字串 “abc”,3在手機按鍵上對應字串 “def”,所以輸出由9個字串組成,分別是 "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"。

解題思路:採用遞迴的思想,每次傳遞的引數分別是:輸入的數字字串digits,記錄要返回字串的集合res,當前遍歷到digits的位置pos,當前得到的字串curCombination。每次根據pos取得digits對應位置的數字,然後根據這個數字去字典裡面查詢手機按鍵上對應的字串,對字串中的每個字元,新增到curCombination的末尾,並

做下一層遞迴。當pos>=digits.length()時,已經遍歷完digits,當前的curCombination就是一個滿足條件的字串,將其新增到res並return。

解題程式碼:(3ms,beats 78.36%)

class Solution {
    String[] dict = new String[] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

	public void letterCombination(String digits, List<String> res, int pos, String curCombination) {
		if (pos >= digits.length()) {
			res.add(curCombination);
			return;
		}
		for (char c : dict[digits.charAt(pos) - '0'].toCharArray()) {
			letterCombination(digits, res, pos + 1, curCombination + c);
		}
	}

	public List<String> letterCombinations(String digits) {
		if (digits == null || digits.length() == 0) {
			return Collections.emptyList();
		}
		List<String> res = new ArrayList<>();
		letterCombination(digits, res, 0, "");
		return res;
	}
}