Share my easy iterative solution, Java, beat over 40.0%

  • 0

    The idea is quite simple, try every possible combination one number after another. For each number, try every character and append it to the string we already have.

    Note we need a "" at the very beginning as the string we already have.

    public class Solution {
        public List<String> letterCombinations(String digits) {
            String[] dict = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            int numDig = digits.length();
            List<String> ret = new ArrayList<String>();
            if(digits==null || digits.length()==0) return ret;
            for(int i=0;i<numDig;i++){
                String curDict = dict[digits.charAt(i)-'0'];
                List<String> curList = new ArrayList<String>();
                for(int j=0;j<curDict.length();j++)
                    for(int k=0;k<ret.size();k++)
                ret = new ArrayList<String>(curList);
            return ret;

Log in to reply

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