2023年2月10日 星期五

17. Letter Combinations of a Phone Number

解題思路

對照的部分用 string array 紀錄,同時以 auto 方式遍歷會比較方便。

程式碼

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        string mapping[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        queue<string> q;
        vector<string> ans;
        if(digits == "")
            return ans;

        q.push("");
        for(int i=0; i<digits.size(); i++)
        {
            int n = q.size();
            while(n--)
            {
                string temp = q.front();
                q.pop();
                for(auto c : mapping[digits[i] - '0'])
                    q.push(temp + c);
            }
        }

        while(!q.empty())
        {
            ans.push_back(q.front());
            q.pop();
        }
        return ans;
    }
};

沒有留言:

張貼留言