Letter Combinations of a Phone Number
给一个string, 每个digit表示一个电话号码的数字, 返回所有可能的英文的组合. 就是dfs
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 |
public class Solution { public List<String> letterCombinations(String digits) { char[][] table = {{}, {'a','b','c'}, {'d','e','f'}, {'g','h','i'}, {'j','k','l'}, {'m','n','o'}, {'p','q','r','s'}, {'t','u','v'}, {'w','x','y','z'}}; List<String> res = new ArrayList<String>(); if(digits == null || digits.length() == 0) return res; dfs(res,"",digits,table); return res; } public void dfs(List<String> res, String tmp, String digits, char[][] table) { if(digits.length() == 0){ res.add(tmp); return; } for(int i = 0; i < table[digits.charAt(0)-'0'-1].length; i++) { dfs(res, tmp + table[digits.charAt(0)-'0'-1][i], digits.substring(1),table); } } } |