码迷,mamicode.com
首页 > 其他好文 > 详细

17. Letter Combinations of a Phone Number

时间:2017-11-10 18:42:03      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:common   commons   code   cal   log   inter   any   repr   app   

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.

 

class Solution {
public:
    vector<string> letterCombinations(string digits) {
    vector<string> res;
    string ss[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    res.push_back("");
    for (int i = 0; i < digits.size(); i++)
    {
        vector<string> tempres;
        string chars = ss[digits[i] - 0];     //当第i个字符digits[i] = “3”,那么digits[i] - ‘0‘把它转化为数字3,则此时chars = “def”
        for (int c = 0; c < chars.size();c++)    //遍历chars里面的字符,再分别与res里面已有的字串结合
            for (int j = 0; j < res.size();j++)
                tempres.push_back(res[j]+chars[c]);
        res = tempres;
    }
    return res;
}
};

//相当于输入“342”。第一次取“3”,res={"d","e","f"},
// 第二次取“4”,对应“ghi”元素分别与res结合再放入临时变量tempers中,
//然后让res=tempers,即res={“dg”,“dh”,“di”,“eg”,“eh”,“ei”,“fg”,“fh”,“fi”}
//第三次取“2”,对应“abc”元素分别与res结合再放入临时变量tempers中,结果很长就不写了。。

 

 https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/ discussion区有很多好的思路,感兴趣可以看看

 

17. Letter Combinations of a Phone Number

标签:common   commons   code   cal   log   inter   any   repr   app   

原文地址:http://www.cnblogs.com/hozhangel/p/7815606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!