Monday, February 25, 2013

[LeetCode] Letter Combinations of a Phone Number

Thought:
It is an easy DP problem, we use the previous result to obtain the current result.

Code:
public class Solution {
    public ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> result = new ArrayList<String>();
        if(digits.length() == 0){
            result.add("");
        }else{
            ArrayList<String> previous = letterCombinations(digits.substring(1));
            char c = digits.charAt(0);
            for(String i: previous){
                if(c=='2'){
                    result.add("a" + i);result.add("b" + i);result.add("c" + i);
                }else if(c=='3'){
                    result.add("d" + i);result.add("e" + i);result.add("f" + i);
                }else if(c=='4'){
                    result.add("g" + i);result.add("h" + i);result.add("i" + i);
                }else if(c=='5'){
                    result.add("j" + i);result.add("k" + i);result.add("l" + i);
                }else if(c=='6'){
                    result.add("m" + i);result.add("n" + i);result.add("o" + i);
                }else if(c=='7'){
                    result.add("p" + i);result.add("q" + i);
                    result.add("r" + i);result.add("s" + i);
                }else if(c=='8'){
                    result.add("t" + i);result.add("u" + i);result.add("v" + i);
                }else if(c=='9'){
                    result.add("w" + i);result.add("x" + i);
                    result.add("y" + i);result.add("z" + i);
                }
            }
        }
        return result;
    }
}

No comments:

Post a Comment