[leetcode] 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;
        if(digits.empty()) return res;
        res.push_back("");
        
        string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        
        for(int i=0; i<digits.size();i++){
            string s = dict[digits[i]-'2'];
            int len = res.size();
            for(int j=0; j<len; j++){
                string tmp = res.front();
                res.erase(res.begin());
                for(int k=0; k<s.size(); k++){
                    res.push_back(tmp + s[k]);
                }
            }
        }
        return res;
    }
};


發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章