1. 程式人生 > >leetcode17Letter Combinations of a Phone Number【佇列】

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

本寶寶實在是不想寫遞迴的寫法了,又繞又慢,況且今天晚上還要做比賽,不想時間都花費到這個上面

佇列的寫法,每次獲取頭部元素,後面加可能的字元,入佇列,寫法很新穎,之前想遞迴百思不得其解

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;
    }
};