1. 程式人生 > >leetcode-17:Letter Combinations of a Phone Number電話號碼的字母組合

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"].

給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。

給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。

示例:

輸入:"23"
輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:先建立一個對映表dict。在遍歷數字時,在dict中取出數字對應的字元str。建立一個臨時字元陣列t,將str的每個字元都連線到 res的每個元素的後面。

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if(digits.empty()) return {};
        vector<string> res{""};
        string dict[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        for(int i=0;i<digits.size();++i)
        {
            string str=dict[digits[i]-'0'];
            vector<string> t;
            for(int j=0;j<str.size();j++)
                for(string s:res) t.push_back(s+str[j]);
            res = t;
        }return res;
    }
};

參考:http://www.cnblogs.com/grandyang/p/4452220.html