leetcode17Letter Combinations of a Phone Number【队列】

版权声明:⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄hiahiahia 欢迎斧正 https://blog.csdn.net/zhou_yujia/article/details/82665301

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

本宝宝实在是不想写递归的写法了,又绕又慢,况且今天晚上还要做比赛,不想时间都花费到这个上面

队列的写法,每次获取头部元素,后面加可能的字符,入队列,写法很新颖,之前想递归百思不得其解

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string>ans;
        if(digits=="")
            return ans;
        ans.push_back("");
        vector<string>ret(10);
        ret[2]="abc";
        ret[3]="def";
        ret[4]="ghi";
        ret[5]="jkl";
        ret[6]="mno";
        ret[7]="pqrs";
        ret[8]="tuv";
        ret[9]="wxyz";
        for(int i=0;i<digits.size();i++){
            int num=ans.size();
            for(int j=0;j<num;j++){
                string tmp=ans[0];
                ans.erase(ans.begin());
                for(int k=0;k<ret[digits[i]-'0'].size();k++){
                    ans.push_back(tmp+ret[digits[i]-'0'][k]);
                }
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/zhou_yujia/article/details/82665301