zoukankan      html  css  js  c++  java
  • LeetCode

    Letter Combinations of a Phone Number

    2013.12.6 19:52

    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.

    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.

    Solution:

      Given a certain digit string and the corresponding mapping between digits [0-9] and letters [a-z],  return all the possible letter combinatios that map to this digit string. Since all the combinations must be enumerated, using DFS is efficient in coding. A mapping array between  digits and letters is needed.

      Code segment is quite short and need no more explanation.

      Time complexity is BIG_PI(i in range(0, len(digit_str))){number of mapping for digit_str[i]}, space complexity is O(len(digit_str)).

    Accepted code:

     1 // 7CE, 2RE, 1WA, 1AC, too bad~
     2 #include <string>
     3 using namespace std;
     4 
     5 class Solution {
     6 public:
     7     vector<string> letterCombinations(string digits) {
     8         // IMPORTANT: Please reset any member data you declared, as
     9         // the same Solution instance will be reused for each test case.
    10         result.clear();
    11         
    12         dfs(digits, 0, "");
    13         
    14         return result;
    15     }
    16 private:
    17     vector<string> result;
    18     string dict[10] = {
    19         " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
    20     };
    21     
    22     void dfs(string &digits, int idx, string str) {
    23         if(idx == digits.length()){
    24             result.push_back(str);
    25             // 1RE here, didn't return
    26             return;
    27         }
    28         
    29         // 7CE here, dict[digits[idx] - '0'], type mismatch
    30         for(int i = 0; i < dict[digits[idx] - '0'].length(); ++i){
    31             // 1RE here, 1WA here, wrong index
    32             dfs(digits, idx + 1, str + dict[digits[idx] - '0'][i]);
    33         }
    34     }
    35 };
  • 相关阅读:
    优先队列的一种实现方式——堆
    iOS 批量打包
    Xcode 8 的 Debug 新特性 —- WWDC 2016 Session 410 & 412 学习笔记
    仿淘宝上拉进入详情页交互的实现
    iOS 10 的适配问题
    集成支付宝钱包支付 iOS SDK 的方法与经验
    Quick Touch – 在 iOS 设备运行的 “Touch Bar”
    iOS 开发中的 Tips(一)
    ReactiveCocoa 中 RACSignal 是怎样发送信号
    自定义下拉刷新控件
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3462044.html
Copyright © 2011-2022 走看看