Java Backtracking solution


  • 0
    P
    class Solution {
        String[] array = {"","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz",""};
        char[] chararray;
        List<String> list = new ArrayList<String>();
        int index = 0;
        public List<String> letterCombinations(String digits) {
            if(digits.length() == 0)
            {
                return list;
            }
            chararray = digits.toCharArray();
            StringBuilder sb = new StringBuilder();
            recursive(sb);
            return list;
        }
        public void recursive(StringBuilder sb)
        {
            if(index == chararray.length)
            {
                list.add(new String(sb.toString()));
                return;
            }
            int number = chararray[index]-48;
            for(int i = 0;i<array[number-1].length();i++)
            {
                sb.append(array[number-1].charAt(i));//number-1
                index++;
                recursive(sb);
                sb.deleteCharAt(sb.length()-1);
                index--;
            }
        }
    }
    

Log in to reply
 

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