leetcode 17 -- Letter Combinations of a Phone Number

it2025-06-10  24

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”].


题意: 输入相似一串数字,返回可能出如今手机按键上的字母。上面有样例。


思路: 这样的不明白循环次数和范围的一般都是用回溯法(递归)来求解,用dfs(深度优先搜索)就可以。和八皇后问题相似。


代码:

//列举出全部可能出现的字符串 string key_val[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; class Solution { public: //深度优先搜索,ret是返回结果,dep是字符串的层次(深度),cur_ret是当前的可能结果,digits是目标字符串 void dfs(vector<string> &ret, int dep, string &cur_ret, string digits){ //假设深度已经到达目标字符串末尾,就返回 if(dep == digits.size()){ ret.push_back(cur_ret); return; } //通过深度获取当前字符串 string cur_str = key_val[digits[dep]-'0']; //对每个字符再进行dfs。 for(int i = 0; i < cur_str.size(); ++i){ cur_ret.push_back(cur_str[i]); dfs(ret, dep+1, cur_ret, digits); //这个保证返回时cur_ret还是为空。 cur_ret.pop_back(); } } vector<string> letterCombinations(string digits){ vector<string>ret; //注意推断0的情况 if(digits.size() == 0){ return ret; } string cur_re(""); dfs(ret, 0, cur_re, digits); return ret; } };

转载于:https://www.cnblogs.com/bhlsheji/p/5341560.html

最新回复(0)