Java recursive solution


  • 0
    M

    I think some recursive solutions does not process '1'. They will return a null list if String digits contain '1'.

    public class Solution{
    
        static final String[] table = { " ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    
        public List<String> letterCombinations(String digits) {
        	List<String> list = new ArrayList<String>();
            if(digits==null || digits.equals("")) return list;
        	letterComb(digits, 0, "", list);
            return list;
        }
        
        private void letterComb(String digits, int offset, String res, List<String> list) {
        	if(digits==null || offset >= digits.length()){
        		list.add(res);
        		return;
        	}
        	char dig = digits.charAt(offset);
        	if(!Character.isDigit(dig)) return;
        	for(int i=0; i<digits.length() && dig=='1'; i++){
        		offset++;
        		dig = digits.charAt(offset);
        	} 
        	String s = table[dig - '0'];
    	for(int j=0; j<s.length(); j++){
    		letterComb(digits, offset+1, res+s.charAt(j), list);
    	}
        }
    }
    

Log in to reply
 

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