电话号码的字母组合-LintCode

来源:互联网 发布:手机使用网络时间不准 编辑:程序博客网 时间:2024/04/30 12:26

Given a digit string excluded 01, 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.

这里写图片描述

注意事项:
以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。

样例:
给定 “23”
返回 [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

#ifndef C425_H#define C425_H#include<iostream>#include<string>#include<vector>using namespace std;class Solution {public:    /*    * @param digits: A digital string    * @return: all posible letter combinations    */    vector<string> letterCombinations(string &digits) {        // write your code here        vector<string> res;        if (digits.empty())            return res;        vector<string> table {"","","abc" , "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };        vector<string> v;        int len = digits.size();        for (int i = 0; i < len; ++i)        {            string str = table[digits[i] - '0'];            v.push_back(str);        }        createVec(res, v, 0);        return res;    }    void createVec(vector<string> &res, vector<string> vec, int pos)    {        if (pos >= vec.size())            return;        if (pos==0)        {            for (int i = 0; i < vec[0].size(); ++i)            {                res.push_back(vec[0].substr(i, 1));            }        }        else        {            string str = vec[pos];            vector<string> v_str;            for (int i = 0; i < res.size(); ++i)            {                for (int j = 0; j < str.size(); ++j)                {                    v_str.push_back(res[i] + str.substr(j, 1));                }            }            res = v_str;        }        createVec(res, vec, ++pos);    }};#endif
阅读全文
0 0
原创粉丝点击