题目描述:

方法1:回溯

class Solution {
public:
    vector<string> result;
    string data;
    string words[8] = {
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz",
    };

    void backtrack(string digits,int Start){
        if(data.size() == digits.size()){
            result.push_back(data);
            return;
        }
        string word = words[digits[Start] - '0' - 2]; //words从0开始,digits从2开始
        for(int i=0;i<word.size();i++){
            data.push_back(word[i]);
            backtrack(digits,Start+1);
            data.pop_back();
        }
    }
    vector<string> letterCombinations(string digits) {
        if(digits.size()==0) return {};
        backtrack(digits,0);
        return result;
    }
};

注:

  • digits[Start] 一定要转为数字,即 -'0'