17.Letter Combinations of a Phone Number
给定一个值为 2~ 9 的字符串,每个数字如下所示,输出所有可能的组合结果。
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路:
一开始没读懂题意,以为是两两结合,其实是所有数字一起的组合。比如“234”,输出模板为“adg"。鉴于可以出现一个数字、多个数字,所以遍历的时候,将之前容器 res存的结果取出,在每个结果的末尾加上当前数字代表的字母,然后再放入新的容器 tmp ,每次循环完 res = tmp; tmp.clear( )。由于第一次循环的时候,res还是空的,防止不能进循环,所以初始res = {""}.
vector<string> letterCombinations(string digits) { if (digits.size() == 0) return {}; string a[] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" }; vector<string> res{""}; //防止首次不能正常循环 int n = digits.size(); for (int i = 0; i < n; i++) { vector<string> tmp; string s = a[digits[i] - '0']; int len_s = s.size(), len_res = res.size(); for (auto res_item : res) { for (auto s_item : s) { tmp.push_back(res_item + s_item); } } res = tmp; tmp.clear(); } return res; }
经验:对于长度不等的字符串,用string的数组存储,比用容器或二维数组好些。
Java 版:
class Solution { public List<String> letterCombinations(String digits) { if(digits.length() == 0) return new ArrayList<String>(); List<String> res = new ArrayList<>(); List<String> tmpResult = new ArrayList<>(); res.add(""); char[][] template = {{'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'} }; for(int i = 0; i < digits.length(); i++){ int n = digits.charAt(i) - '0'; for(String s : res){ for(char c : template[n-2]) tmpResult.add(s + c); } res.clear(); res.addAll(tmpResult); tmpResult.clear(); } return res; } }