17. Letter Combinations of a Phone Number

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"};
    if(digits.size() == 0 ) return res;
    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中,
//接着=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区有很多好的思路,感兴趣可以看看

 
posted @ 2017-11-10 17:15  hozhangel  阅读(254)  评论(0)    收藏  举报