Letter Combinations of a Phone Number

£神魔★判官ぃ 2022-01-07 23:55 308阅读 0赞

题目描述:

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.

200px-Telephone-keypad2.svg.png

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

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

  

  这道题不算难,想想就出来了。

solution:

  1. vector<string> letterCombinations(string digits) {
  2. int n = digits.size();
  3. vector<string> res;
  4. if(n == 0)
  5. return res;
  6. res.push_back("");
  7. string numap[] = {
  8. "#","#","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
  9. for (int i = 0;i < n;++i)
  10. {
  11. vector<string> tmp;
  12. for(int j = 0;j < res.size();++j)
  13. for(int k = 0;k < numap[digits[i]-'0'].size();++k)
  14. tmp.push_back(res[j] + numap[digits[i]-'0'][k]);
  15. res = tmp;
  16. }
  17. return res;
  18. }

  此题还有其他解法,《编程之美》中也有相似题目,暂时先这样了。

转载于:https://www.cnblogs.com/gattaca/p/4315884.html

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读