问题描述:
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"].问题分析:
这可以看作一个组合问题
1.设置一个结果集result值为空
2.对每个digit进行遍历,将其对应的字符添加分别与result结果集中的每个元素组合即可
下面是具体实现:
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> result; if(digits.empty()) return vector<string>(); vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; result.push_back(""); for(int i = 0; i < digits.size(); i++) { int num = digits[i] - '0'; if(num < 0 || num > 9) break; string candidate = v[num]; if(candidate.empty()) continue;//出现数字0和1 vector<string> tmp; // 将result和candidate的字符串组合一下 for(int j = 0 ; j < candidate.size() ; j++) { for(int k = 0 ; k < result.size() ; k++) { tmp.push_back(result[k] + candidate[j]); } } result.swap(tmp); } return result; }};好了,就先记这么多吧~
新闻热点
疑难解答