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.

《LeetCode | Letter Combinations of a Phone Number》

Input:Digit string "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.

思路:

本题目本身只是一个简单的递归循环。

代码:

class Solution {
public:
vector<string> result;
    vector<string> letterCombinations(string digits) {
        vector<vector<char>> keyboard;
        int total = 0;
        for(int i = 0; i < 8; i++){
            int num = 3;
            if(i == 5 || i == 7){
                num = 4;
            }
            vector<char> tmp;
            for(int j = 0; j < num; j++){
                tmp.push_back('a' + total++);
            }
            keyboard.push_back(tmp);
        }
        
        string cur;
        generateCombinations(keyboard, digits, 0, cur);
        
        return result;
    }
    
    void generateCombinations(vector<vector<char>> &keyboard, string &digits, int index, string & cur){
        if(index == digits.size()){
            result.push_back(cur);
            return;
        }
        
        for(int i = 0; i < keyboard[digits[index] - '2'].size(); i++){
            cur.push_back(keyboard[digits[index] - '2'][i]);
            generateCombinations(keyboard, digits, index + 1, cur);
            cur.pop_back();
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11695885
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞