Letter Combinations of a Phone Number

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.

这个可以用递归做,主要思想是尝试,也就是Backtracking,这个还是比较好理解的。
public List<String> letterCombinations(String digits) {
		List<String> result = new ArrayList<String>();
		if (digits == null || digits.length() == 0) {
			return result;
		}
	String[] strs = { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv",
				"wxyz" };
		List<String> ls = new ArrayList<String>();
		String temp = digits;
		if (digits.length() > 1) {
			temp = digits.substring(0,digits.length() - 1);
			List<String> lett = letterCombinations(temp);
			
			int tem = Integer.valueOf(digits.substring(digits.length() - 1));
			if (tem != 1 && tem != 0) {
				for (String str : lett) {
					for (int i = 0; i < strs[tem-2].length(); i++) {
						String s = str + strs[tem - 2].charAt(i);
						ls.add(s);
					}
				}
			}else{
				ls = lett;
			}
			 
		}
		if (digits.length() == 1) {
			String temp1 = digits;
			if (Integer.valueOf(temp1) != 1 && Integer.valueOf(temp1) != 0) {
				for (int i = 0; i < strs[Integer.valueOf(temp1) - 2].length(); i++) {
					String s = "" + strs[Integer.valueOf(temp1) - 2].charAt(i);
					ls.add(s);
				}
			}
		}

		return ls;
	}

猜你喜欢

转载自plan454.iteye.com/blog/2189215