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"].
import java.util.ArrayList; import java.util.HashMap; public class Solution { private HashMap<Character,String> map; public void setup(){ map = new HashMap<Character,String>();//character ' ',string " " map.put('1', ""); map.put('2', "abc"); map.put('3', "def"); map.put('4', "ghi"); map.put('5', "jkl"); map.put('6', "mno"); map.put('7', "pqrs"); map.put('8', "tuv"); map.put('9', "wxyz"); map.put('0', ""); } public ArrayList<String> letterCombinations(String digits) { // Start typing your Java solution below // DO NOT write main() function setup(); ArrayList<String> solutions = new ArrayList<String>(); recursion(0,digits,solutions,new String()); return solutions; } public void recursion(int start,String digits,ArrayList<String> result,String temp){ if(temp.length() > digits.length()){ return; } if(temp.length() == digits.length()){//has to be temp's length not start result.add(temp); return; } for(int i = start ; i < digits.length();i++){ String letter = map.get(digits.charAt(i)); for(int j = 0;j < letter.length();j++){ recursion(i+1,digits,result,temp+letter.charAt(j) );//level is i not start } } } }
mistake: inner loop the start should be number of level not the start otherwise will missing one more loop