Letter Combinations of a Phone Number--LeetCode

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

Solution:

使用遞歸算法來解決問題:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> answer;
        string letter[10] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        if (digits.length() == 0) return answer;
        else if (digits.length() == 1)
        {
            for(int a = 0; a < letter[digits[0] - '0'].length(); a++)
            {
                string s = "";
                s += letter[digits[0] - '0'][a];
                answer.push_back(s);
            }
        }
        else
        {
            for(int a = 0; a < letter[digits[0] - '0'].length(); a++)
            {
                vector<string> temp = letterCombinations(digits.substr(1));
                for (int b = 0; b < temp.size(); b++)
                {
                    string s = letter[digits[0] - '0'][a] + temp[b];
                    answer.push_back(s);
                }
            }
        }
        return answer;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章