LeetCode-17. Letter Combinations of a Phone Number

Description

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

Note

Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution 1(C++)

class Solution{
public:
    vector<string> alpha={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if(digits.empty()) return res;
        helper(res, digits, "", 0);
        return res;
    }

    void helper(vector<string>& res, string digits, string s, int n){
        if(n == digits.size()) { res.push_back(s); return; }
        string temp = alpha[digits[n]-'0'];
        for(int i=0; i<temp.size(); i++){
            helper(res, digits, s+temp[i], n+1);
        }
    }
};

後續更新

其他類似的題目可參考:

算法分析

這道題難度不大,主要是要分析清楚邏輯。問題可以轉換成一個比較經典的全排序的問題。使用回溯不難解決。

程序分析

略。

發佈了362 篇原創文章 · 獲贊 108 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章