Skip to content

Latest commit

 

History

History
61 lines (50 loc) · 1.66 KB

17电话号码的字母组合.md

File metadata and controls

61 lines (50 loc) · 1.66 KB

题目描述

https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

"23"
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

说明:

尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。


思路一

就按字典序来
注意char与string的转换

class Solution {
public:
    vector<string> letterCombinations(string digits) {
      map<char, string> button;
        button['2'] = "abc"; 
        button['3'] = "def";
        button['4'] = "ghi";
        button['5'] = "jkl";
        button['6'] = "mno";
        button['7'] = "pqrs";
        button['8'] = "tuv";
        button['9'] = "wxyz";
        
        vector<string> s;
        
        for(int i=0; i<digits.size(); i++){
            
            if( i==0 ){
                for(int j=0; j<button[digits[i]].size(); j++){
                	string temp;
                	temp.append(1, button[digits[i]][j]);
                	
                    s.push_back(temp);   
                }
            }
            else{
                int len = s.size();
                for(int t=0; t<len; t++){
                    for(int j=0; j<button[digits[i]].size(); j++){
                        s.push_back(s[0] + button[digits[i]][j]); 
                    }
                    
                    s.erase(s.begin());
                }   
            }
        }
        
        return s;
    }
};