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:
分析:
看到返回所有,应该想到回溯,即DFS。
public class Solution { public List<String> letterCombinations(String digits) { //存候选 String[] ss = {" ", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; List<String> res = new ArrayList<String>(); dfs(res, digits.length(), ss, digits, new StringBuffer()); return res; } public void dfs(List<String> res, int remain, String[] ss, String digits, StringBuffer sb){ if(remain==0){ res.add(sb.toString()); return; } String s = ss[digits.charAt(0)-'0']; //对所有情况进行处理 for(int i=0; i<s.length(); i++){ sb.append(s.charAt(i)); dfs(res, remain-1, ss, digits.substring(1), sb); sb.deleteCharAt(sb.length()-1); } } }