zoukankan      html  css  js  c++  java
  • 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.

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

    Example:

    Input: "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.

    这道题其实用递归写更好一些,但是考虑到递归可能会引起栈溢出,我还是用循环来做,方法如下:最外层循环是遍历输入的数字序列,每次读入一个数字,并找到与之相对应的字符串,然后遍历该字符串,同时遍历字符向量,逐个将字符与字符向量中的字符串拼接并且放入临时变量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 };
  • 相关阅读:
    8086汇编学习小记王爽汇编语言实验12
    8086汇编学习小记王爽汇编语言课程设计1
    activeMQ 持久化配置 kevin
    snmpwalk kevin
    tcp benchmark kevin
    apache camel 条件路由 kevin
    netty 并发访问测试配置 kevin
    snmp常见操作 kevin
    转发:RocketMQ与kafka的对比 kevin
    centos jdk 下载 kevin
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/9853598.html
Copyright © 2011-2022 走看看