Given a digit string excluded 01
, 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.
是一个典型的dfs。 将一个 arraylist 向下传递,达到保存条件的时候,放进去。递归
public class Solution { /* * @param digits: A digital string * @return: all posible letter combinations */ String[] strarr = new String[] {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; public List<String> letterCombinations(String digits) { // write your code here List<String> ans = new ArrayList<String>(); if(digits.length() == 0){ return ans; } work(digits,0,"",ans); return ans; } public void work(String target,int count,String str,List<String> ans){ if(target.length() == count){ ans.add(str); return; } int temp = target.charAt(count) - '0'; if(temp == 0 || temp == 1){ work(target,count+1,str,ans); }else{ for(int i = 0;i<strarr[temp].length();i++){ work(target,count+1,str+strarr[temp].charAt(i),ans); } } } }