leetcode-17. Letter Combinations of a Phone Number

    xiaoxiao2021-03-25  193

    leetcode-17. 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. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

    按照电话数字把对应的字母写出来 用迭代的方法,

    class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; if(digits.empty()) return res; string dict[] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; letterCombinationsDFS(digits, dict, 0, "", res); return res; } void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res){ if(level == digits.size()) res.push_back(out); else{ string str= dict[digits[level] - '2']; //注意是'2',不是2 for(int i = 0; i < str.size(); ++i){ out.push_back(str[i]); letterCombinationsDFS(digits, dict, level + 1, out, res); out.pop_back(); //为什么要pop_back? } } } };
    转载请注明原文地址: https://ju.6miu.com/read-2285.html

    最新回复(0)