---
title: "Letter Combinations of a Phone Number "
author: "plan454"
date: "2015-03-05T22:30:11Z"
tags: []
categories: ["非技术"]
slug: "letter-combinations-of-a-phone-number"
draft: false
lastmod: "2015-03-05T22:30:11Z"
id: 2189215
url: "https://plan454.iteye.com/blog/2189215"
---

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: .
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

这个可以用递归做，主要思想是尝试，也就是Backtracking，这个还是比较好理解的。

```java
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;
	}
```