My easy dfs solution


  • 0
    J
    public class Solution {
        List<String> res;
        public List<String> letterCombinations(String digits) {
            res=new ArrayList<String>();
            if(digits==null||digits.length()==0) return res;
            ArrayList<Character> solu=new ArrayList<Character>();
            dfs(digits, 0, solu);
            return res;
        }
        public void dfs(String digits, int level, ArrayList<Character> solu){
            if(level==digits.length()){
                char[] arr = new char[solu.size()];
                for(int i=0; i<solu.size(); i++){
                    arr[i] = solu.get(i);
                }
                res.add(String.valueOf(arr));
                return;
            }
            String str=getStr(digits.charAt(level));
            for(int i=0;i<str.length();i++){
                solu.add(str.charAt(i));
                dfs(digits, level+1, solu);
                solu.remove(solu.size()-1);
            }
            
        }
        public String getStr(Character c){
            switch(c){
                case '0':
                    return "";
                case '1':
                    return "";
                case '2':
                    return "abc";
                case '3':
                    return "def";
                case '4':
                    return "ghi";
                case '5':
                    return "jkl";
                case '6':
                    return "mno";
                case '7':
                    return "pqrs";
                case '8':
                    return "tuv";
                case '9':
                    return "wxyz";
            }
            return "";
        }
    }

Log in to reply
 

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