A simple java recursive solution.


  • 0
    S
    public class Solution {
    	 
    	 String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    	 
    	 public List<String> letterCombinations(String n) {
    
            if(n.length() == 0)
                return new ArrayList<String>();
    		 int number[] = new int[n.length()];
    		 for(int i = 0; i < n.length(); i++){
    			 number[i] = Integer.valueOf(n.charAt(i))-'0';
    		 }
    		 List<String> result = new ArrayList<String>();
    		 StringBuilder builder = new StringBuilder();
    		 letterCombinationUtil(number, 0, builder, number.length, result);
             return result;		 
    
    		}
    		
    	 public void letterCombinationUtil(int[] number, int current, StringBuilder output, int n, List<String> result){
    		 
    		 if(current == n){
    			 result.add(output.toString());
    			 return;
    		 }
    		 
    		 for(int i = 0; i < mapping[number[current]].length(); i++){
    			 
    			 output.append(mapping[number[current]].charAt(i));
    			 letterCombinationUtil(number, current+1, output, n, result);
    			 output.setLength(output.length()-1);
    			 if(number[current] == 0 || number[current] == 1){
    				 return;
    			 }
    		 }
    		 
    		 
    	 }
    		
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.