問題描述:
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; }};好了,就先記這么多吧~
新聞熱點
疑難解答