leetcode-17:Letter Combinations of a Phone Number電話號碼的字母組合
阿新 • • 發佈:2018-12-22
題目:
Given a string containing digits from A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" Output: |
給定一個僅包含數字 給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。 示例: 輸入:"23" 輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. |
思路:先建立一個對映表dict。在遍歷數字時,在dict中取出數字對應的字元str。建立一個臨時字元陣列t,將str的每個字元都連線到 res的每個元素的後面。
class Solution { public: vector<string> letterCombinations(string digits) { if(digits.empty()) return {}; vector<string> res{""}; string dict[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; for(int i=0;i<digits.size();++i) { string str=dict[digits[i]-'0']; vector<string> t; for(int j=0;j<str.size();j++) for(string s:res) t.push_back(s+str[j]); res = t; }return res; } };