[Leetcode] Letter Combinations of a Phone Number

客官°小女子只卖身不卖艺 2021-12-03 07:27 318阅读 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"].

模拟!

  1. 1 class Solution {
  2. 2 public:
  3. 3 string key[10];
  4. 4 void initKey() {
  5. 5 key[0] = " ";
  6. 6 key[1] = "";
  7. 7 key[2] = "abc";
  8. 8 key[3] = "def";
  9. 9 key[4] = "ghi";
  10. 10 key[5] = "jkl";
  11. 11 key[6] = "mno";
  12. 12 key[7] = "pqrs";
  13. 13 key[8] = "tuv";
  14. 14 key[9] = "wxyz";
  15. 15 }
  16. 16 void findNext(vector<string> &res, string &digits, string s, int idx) {
  17. 17 if (s.length() == digits.length()) {
  18. 18 res.push_back(s);
  19. 19 return;
  20. 20 }
  21. 21 int k = digits[idx] - '0';
  22. 22 for (int i = 0; i < key[k].length(); ++i) {
  23. 23 findNext(res, digits, s + key[k][i], idx + 1);
  24. 24 }
  25. 25 }
  26. 26 vector<string> letterCombinations(string digits) {
  27. 27 initKey();
  28. 28 vector<string> res;
  29. 29 string s;
  30. 30 findNext(res, digits, s, 0);
  31. 31 return res;
  32. 32 }
  33. 33 };

转载于:https://www.cnblogs.com/easonliu/p/3646803.html

发表评论

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

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

相关阅读