xinyu04

导航

LeetCode 17 Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Solution

用一个 \(vector\) 来存储每个数字的映射,如果当前的 \(res\) 长度达到和 \(digit\) 一样时,就加入答案

点击查看代码
class Solution {
private:
    vector<string> ans;
    string res = "";
    vector<string> mp = {"","", "abc",
                        "def","ghi","jkl",
                        "mno","pqrs","tuv","wxyz"};
    
    void dfs(string digits, int val, string res, int idx){
        if(res.size()==digits.size()){
            ans.push_back(res);return;
        }
        for(int i=0;i<mp[val].size();i++){
            dfs(digits, digits[idx+1]-'0', res+mp[val][i],idx+1);
        }
    }
    
public:
    vector<string> letterCombinations(string digits) {
        int n = digits.size();
        if(n==0)return ans;
        dfs(digits, digits[0]-'0', res, 0);
        return ans;
    }
};

posted on 2022-08-10 15:39  Blackzxy  阅读(11)  评论(0编辑  收藏  举报