leetcode 17. Letter Combinations of a Phone Number

import java.util.ArrayList;
import java.util.List;

//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"].


public class Solution {
	
	public static void main(String[] args) {
		String a = "";
		List<String> result = letterCombinations(a);
		for(int i = 0;i<result.size();i++){
			System.out.println(result.get(i));
		}
	}
	
	public static List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if(digits.length() == 0){																			//输入为空串直接返回List
        	return result;
        }
        String[] map = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        char[] tmp = new char[digits.length()];
        find(digits, 0, tmp, map, result);
        return result;
    }
	
	public static void find(String digit, int index, char[] tmp, String[] map, List<String> result){		//深度遍历digits所有字符可能的情况
		if(index == digit.length()){																		//当遍历到底,则将此种情况加入List中
			result.add(new String(tmp));
			return;
		}
		char tmpChar = digit.charAt(index);																	//得到当前层digits中的字符
		for(int i = 0;i<map[tmpChar-'0'].length();i++){														//搜寻当前数字字符代表的所有字母字符
			tmp[index] = map[tmpChar-'0'].charAt(i);														//存入tmp中
			find(digit, index+1, tmp, map, result);															//递归遍历下一层
		}
	}
	
}


你可能感兴趣的:(java,LeetCode)