#LeetCode:17. Letter Combinations of a Phone Number

遞迴展開所有結果即可。

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);
  }
};
廣告

Comment

There is no comment on this post. Be the first one.

發表迴響

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

%d 位部落客按了讚: