My java solution with DFS


  • 0
    G
    class Solution {
    	public List<String> letterCombinations(String digits) {
    		List<String> res = new ArrayList<String>();
            if(digits.length()==0) return res;
    		String[] phone = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    		dfs(phone,digits,res,0,"");
    		return res;
    	}
    	public void dfs(String[] phone,String digits,List<String> res, int index, String str) {
    		if(index<digits.length()) {
    			int digit = digits.charAt(index)-'0';
    			String chs = phone[digit];
    			for(int i=0;i<chs.length();i++) {
    				dfs(phone,digits,res,index+1,str+chs.charAt(i));
    			}
    		}else {
    		    res.add(str);
    		}
    	}
    }
    

Log in to reply
 

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