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 };
  • 相关阅读:
    Dialog 对话框的文字与输入框不对齐
    ag-grid动态生成表头及绑定表数据
    ag-grid实时监测复选框变化
    Java-分页工具类
    Java-日期转换工具类
    文件上传与下载
    IDEA的安装与激活
    熟悉IDEA工具的使用
    缓存三大问题的解决办法
    制作一个省份的三级联动菜单
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/9853598.html
Copyright © 2011-2022 走看看