1. 程式人生 > >LeetCode-電話號碼的字母組合

LeetCode-電話號碼的字母組合

給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。

給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。

示例:

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

說明:

儘管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。

class Solution {
    public List<String> letterCombinations(String digits) {
 
    	ArrayList<String> list = new ArrayList<>();
    	
    	if(digits==null||digits.length()==0)
    	{
    		return list;
    	}
    	
    	String[] phoneNumbers = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    	dfsPhoneNumbers(digits,0,phoneNumbers,list,new StringBuffer());
    	
    	return list;
    }

	private void dfsPhoneNumbers(String digits,int index, String[] phoneNumbers, ArrayList<String> list,StringBuffer buffer) 
	{
		// TODO Auto-generated method stub
		if(index==digits.length())
		{
			list.add(buffer.toString());
			return;
		}
		String phoneNumberString = phoneNumbers[digits.charAt(index)-'0'];
		
		for(int i=0;i<phoneNumberString.length();++i)
		{
			buffer.append(phoneNumberString.charAt(i));
			dfsPhoneNumbers(digits, index+1, phoneNumbers, list, buffer);
			buffer.deleteCharAt(buffer.length()-1);
		}
	    
		
	}
}