Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();
        if (digits == null || !digits.matches("[2-9]+")) {
            return res;
        }
        String[] letters = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        StringBuilder sb = new StringBuilder();
        help(digits, letters, 0, res, sb);
        return res;
    }
    
    private void help(String digits, String[] letters, int i, List<String> res, StringBuilder sb) {
        if (sb.length() == digits.length()) {
            res.add(sb.toString());
            return;
        }
        
        for (int j = i; j < digits.length(); j++) {
            String letter = letters[(int)digits.charAt(i) - 50];
            for (int k = 0; k < letter.length(); k++) {
                sb.append(letter.charAt(k));
                help(digits, letters, j + 1, res, sb);
                sb.deleteCharAt(sb.length() - 1);
            }
        }
    }
}