#LeetCode:17. Letter Combinations of a Phone Number

灆洢 2018-10-08 09:23:38

遞迴展開所有結果即可。

C++(0ms)

/*******************************************************/
/* LeetCode 17. Letter Combinations of a Phone Number  */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2018/10/08                                 */
/*******************************************************/
#include <vector>

class Solution {
private:
  const vector<string> _telephoneButtonsMap = {
    " ", "", "abc",
    "def", "ghi", "jkl",
    "mno", "pqrs", "tuv",
    "wxyz"};
public:
  vector<string> indexLetterCombinations(const string &digits, int index, vector<string> &prefixStrings){
    if(index == digits.length()) return prefixStrings;

    string buttonCharacters = _telephoneButtonsMap[digits[index]-'0'];
    if(buttonCharacters.length() > 0 && prefixStrings.size() == 0){
      prefixStrings.push_back("");
    }

    vector<string> result;
    for(int i = 0 ; i < prefixStrings.size() ; ++i){
      for(int j = 0 ; j < buttonCharacters.length() ; ++j){
        result.push_back(prefixStrings[i] + buttonCharacters[j]);
      }
    }

    return indexLetterCombinations(digits, index + 1, result);
  }

  vector<string> letterCombinations(string digits) {
    vector<string> emptyVector;
    return indexLetterCombinations(digits, 0, emptyVector);
  }
};

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料