Java Solution By Recursion


  • 0
    B
    class Solution {
        public String[] str = {"","","abc", "def","ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        public List<String> letterCombinations(String digits) {
            List<String> list = new ArrayList();
            String s = "";
            if(get(digits, 0, s, list) == 1) //
                return list;
            return new ArrayList();
        }
        public int get(String digits, int i, String s, List<String> list){ //此函数将实现 自 i之后的数字串的list
            if(digits.length() - i == 0) return 0;  //flag
            if(digits.length() - i == 1) {
                char ch = digits.charAt(i);
                int k = ch - '0';
                if(str[k].length() == 0) return 0;   //flag
                else{
                    for(int j = 0; j < str[k].length(); j++){
                        String s2 = s;
                        s2 += str[k].charAt(j);
                        list.add(s2);
                    }
                }
            }
            else{
                char ch = digits.charAt(i);
                int k = ch - '0';
                if(str[k].length() == 0) return 0;  //flag
                else{
                    for(int j = 0; j < str[k].length(); j++){
                        String s2 = s;
                        s2 += str[k].charAt(j);
                        if(get(digits, i+1, s2, list) == 0)
                            return 0;
                    }
                }
            }
            return 1;
        }
    }
    

Log in to reply
 

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