Letter Combinations of a Phone Number

描述

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.

Phone Keyboard

Figure: Phone Keyboard

Input:Digit string "23"

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.

分析

递归

  1. // Letter Combinations of a Phone Number
  2. // 时间复杂度O(3^n),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
  6. "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
  7. vector<string> letterCombinations (const string &digits) {
  8. vector<string> result;
  9. if (digits.empty()) return result;
  10. dfs(digits, 0, "", result);
  11. return result;
  12. }
  13. void dfs(const string &digits, size_t cur, string path,
  14. vector<string> &result) {
  15. if (cur == digits.size()) {
  16. result.push_back(path);
  17. return;
  18. }
  19. for (auto c : keyboard[digits[cur] - '0']) {
  20. dfs(digits, cur + 1, path + c, result);
  21. }
  22. }
  23. };

迭代

  1. // Letter Combinations of a Phone Number
  2. // 时间复杂度O(3^n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
  6. "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
  7. vector<string> letterCombinations (const string &digits) {
  8. if (digits.empty()) return vector<string>();
  9. vector<string> result(1, "");
  10. for (auto d : digits) {
  11. const size_t n = result.size();
  12. const size_t m = keyboard[d - '0'].size();
  13. // resize to n * m
  14. for (size_t i = 1; i < m; ++i) {
  15. for (size_t j = 0; j < n; ++j) {
  16. result.push_back(result[j]);
  17. }
  18. }
  19. for (size_t i = 0; i < result.size(); ++i) {
  20. result[i] = result[i] + keyboard[d - '0'][i/n];
  21. }
  22. }
  23. return result;
  24. }
  25. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/brute-force/letter-combinations-of-a-phone-number.html