LeetCode 17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.git

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.app

Example:spa

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

Note:code

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

 

這道題其實用遞歸寫更好一些,可是考慮到遞歸可能會引發棧溢出,我仍是用循環來作,方法以下:最外層循環是遍歷輸入的數字序列,每次讀入一個數字,並找到與之相對應的字符串,而後遍歷該字符串,同時遍歷字符向量,逐個將字符與字符向量中的字符串拼接而且放入臨時變量t,每次讀完一個數字將t賦值給res,直到讀完全部的數字,這道題的時間複雜度爲指數複雜度。遞歸

 

 1 class Solution {
 2 public:
 3     vector<string> letterCombinations(string digits) {
 4         if (digits.size() == 0)
 5             return {};
 6         vector<string> res{""};
 7         string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 8         for (int i = 0; i < digits.size(); i++)
 9         {
10             vector<string> t;
11             string str = dict[digits[i] - '0'];
12             for (int j = 0; j < str.size(); j++)
13             {
14                 for (auto s : res)
15                     t.push_back(s + str[j]);
16             }
17             res = t;
18         }
19         return res;
20     }
21 };
相關文章
相關標籤/搜索