【LeetCode系列】電話號碼的字母組合 Letter Combinations of a Phone Number

題目描述: LeetCode原題地址
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.
給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。
給出數字到字母的映射如下(與電話按鍵相同)。注意 1 不對應任何字母。
電話九鍵
樣例:
輸入:“23”
輸出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

思路: 用回溯法的思想,本質上是遞歸調用。首先建立一個數組,分別表示0-9對應的字母,level表示層,比如樣例中的2是第0層,3是第1層以此類推。先遍歷第0層的2,2表示abc,把第0個數a加到當次結果combination中,然後進入下一層3,3表示def,把第0個數d加到當次結果combination中,此時level已經到了最後一層,將當次結果combination放入結果集result中。

代碼:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if(digits.empty()){
            return {};
        }
        //結果集
        vector<string> result;
        backtrack(result, "", digits, 0);
        return result;
    }
    
    void backtrack(vector<string> &result, string combination, string digits, int level){
        //分別代表0-9
        string phone[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        if(level == digits.size()){
            result.push_back(combination);
            return;
        }
        string str = phone[digits[level] - '0'];
        //循環遍歷每一個數字代表的字母組合
        for(int i = 0; i < str.size(); i++){
            //combination + string(1, str[i])的意思是每次循環把phone[level]對應的某個i字符加到當前combination字符串後
            backtrack(result, combination + string(1, str[i]), digits, level + 1);
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章