3ms Java solution with easiest recursive function


  • 0
    J

    public class Solution
    {

    char[][] lib = new char[][]{{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'}, {'m', 'n', 'o'},{'p', 'q', 'r', 's'}, {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}};
    public List<String> letterCombinations(String digits)
    {
        int length = digits.length();
        List<String> result = new LinkedList<>();
        char[] c = digits.toCharArray();
    
        if (digits.isEmpty()) return result;
        for (int i = 0; i < length; i++)
        {
            if (c[i] == '0' || c[i] == '1')
                return result;
        }
        recursive(digits,"",result);
        return result;
    }
    void recursive(String dig,String c,List<String> list)
    {
    
        for(int i=0;i<(lib[dig.charAt(0)-'2'].length);i++)
        {
            String result = c+lib[dig.charAt(0)-'2'][i];
            if(dig.length()>1)
                recursive(dig.substring(1),result,list);
            else
                list.add(result);
        }
    }
    

    }


Log in to reply
 

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