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.

Letter Combinations of a Phone Number

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.

  

  这道题不算难,想想就出来了。

solution:

vector<string> letterCombinations(string digits) {
    int n = digits.size();
    vector<string> res;
    if(n == 0)
        return res;
    res.push_back("");
    string numap[] = {"#","#","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    for (int i = 0;i < n;++i)
    {
        vector<string> tmp;
        for(int j = 0;j < res.size();++j)
            for(int k = 0;k < numap[digits[i]-'0'].size();++k)
                tmp.push_back(res[j] + numap[digits[i]-'0'][k]);
        res = tmp;
    }
    return res;
}

  此题还有其他解法,《编程之美》中也有相似题目,暂时先这样了。

转载于:https://www.cnblogs.com/gattaca/p/4315884.html

上一篇:php – 通过向多个买家销售商品来查找最高总价,受限于用户输入可以进行多少单独销售


下一篇:php – 生成所有可能的组合