Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

17. Letter Combinations of a Phone Number #21

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

无非是几重循环即可搞定,为了麻烦麻烦自己,采用了递归的想法,虽然代码简单了些,牺牲了空间和时间

public class Solution { public List letterCombinations(String digits) { List res = new ArrayList(); if(!digits.isEmpty()) { findRes(digits, "", 0, res); } return res; }

private void findRes(String digits, String sum, int pos, List<String> res) {
    if(pos == digits.length()) {
        res.add(sum);
        return;
    }
    String[] letter = getInfo(digits.charAt(pos));
    for(int i = 0; i < letter.length; i++) {

//每次递归都在循环里调用findRes()函数 findRes(digits, sum + letter[i], pos + 1, res); } }

private String[] getInfo(char c) {
    switch(c) {
        case '2':
            return new String[] {"a", "b", "c"};
        case '3':  
            return new String[] {"d", "e", "f"};  
        case '4':  
            return new String[] {"g", "h", "i"};  
        case '5':  
            return new String[] {"j", "k", "l"};  
        case '6':  
            return new String[] {"m", "n", "o"};  
        case '7':  
            return new String[] {"p", "q", "r", "s"};  
        case '8':  
            return new String[] {"t", "u", "v"};  
        case '9':  
            return new String[] {"w", "x", "y", "z"};  
    }
    return new String[] {};
}

}

Shawngbk commented 7 years ago