LeetCode 017. Letter Combinations of a Phone Number

xiaoxiao2021-02-27  348

问题

        Given a digit string, return all possible letter combinations that the number could represent.

        A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

分析

从头开始遍历数字表第一个数字,直接将数字对应的各个结果添加到result中非第一个数字,遍历result中已有的所有的字符串,在每一个字符串的末尾,分别加上当前数字所对应的字母数字与键盘九宫格相对应

解析

vector<string> letterCombinations(string digits) { vector<string> result; vector<string> tmp; string strs[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; result.push_back(""); for (int i = 0; i < digits.size(); i++){ int index = digits[i] - '0'; for (int k = 0; k < result.size(); k++){ for (int j = 0; j < strs[index].size(); j++){ string s = result[k] + strs[index][j]; tmp.push_back(s); } } result = tmp; tmp.clear(); } return result; }
转载请注明原文地址: https://www.6miu.com/read-3559.html

最新回复(0)