Java recrusive solution


  • 0
    J
        public List<String> letterCombinations(String digits) {
            ArrayList<String> result = new ArrayList<>();
            if (digits.length() == 0) return result;
            String[] mapping = new String[] {" ", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            char[] path = new char[digits.length()];
            comb(digits, path, 0, mapping, result);
            return result;
        }
        
        private void comb(String digits, char[] path, int start, String[] mapping, List<String> result) {
            if (start >= path.length) {
                result.add(new String(path));
                return;
            }
            int idx = digits.charAt(start) - '0';
            String trans = mapping[idx];
            for (int i = 0; i < trans.length(); i++) {
                path[start] = trans.charAt(i);
                comb(digits, path, start + 1, mapping, result);
            }
        }
    

Log in to reply
 

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