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.
public class Solution { private String[] alpha = new String[] { " ", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; private StringBuilder word; private void dfs(List<String> res, String digits, int cur) { if (cur >= digits.length()) { res.add(word.toString()); } else { for (int i = 0; i < alpha[digits.charAt(cur) - '0'].length(); ++i) { word.append(alpha[digits.charAt(cur) - '0'].charAt(i)); dfs(res, digits, cur + 1); word.deleteCharAt(word.length() - 1); } } } public List<String> letterCombinations(String digits) { List<String> ret = new ArrayList<String>(); word = new StringBuilder(); dfs(ret, digits, 0); return ret; } }
解题思路:穷举所有可能的字符串使用dfs来解决。
class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): def dfs(num, string, res): if num == length: res.append(string) return for letter in dict[digits[num]]: dfs(num+1, string+letter, res) dict = {'2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'], '6':['m','n','o'], '7':['p','q','r','s'], '8':['t','u','v'], '9':['w','x','y','z'] } res = [] length = len(digits) dfs(0, '', res) return res
class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): alpha = [" ", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] res = [] word = [] def dfs(cur): if cur >= len(digits): res.append(''.join(word)) else: for x in alpha[(int)(digits[cur]) - (int)('0')]: word.append(x) dfs(cur + 1) word.pop() dfs(0) return res