Java - Simple to understand DFS solution


  • 0
    T
    public class Solution {
        public List<String> letterCombinations(String digits) {
            String[] combinations = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
            List<String> result = new ArrayList<>();
            if(digits.length()==0) return result;
            
            helper(digits, 0, combinations,result,"");
            return result;
        }
        
        private void helper(String digits, int start, String[]combinations,List<String> result,String str){
            if(start==digits.length()){
                result.add(str);
                return;
            }
            
            int pos = Character.getNumericValue(digits.charAt(start));
            
            String s = combinations[pos-2];
            for(int i = 0;i<s.length();i++){
                char c = s.charAt(i);
                helper(digits, start+1, combinations, result,str+c );
            }
            
        }
    }
    

Log in to reply
 

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