回溯Leetcode 17 Letter Combinations of a Phone Number
阿新 • • 發佈:2018-12-28
Leetcode 17
Letter Combinations of a Phone Number
- Problem Description:
電話上每個數字都有對應的字母,如下圖所示,數字0和數字1沒有對應的字母,數字2對應的字母包括“abc”,現輸入一串數字要求輸出所有可能的字母組合。
具體的題目資訊:
https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ - Example:
- Solution: 【參考討論區程式碼】
class Solution {
public :
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.length() == 0) return res;
res.push_back("");
vector<string> temp;
vector<string> Phone={"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
for(int i = 0; i < digits.length(); i++) {
int num = digits[i]-'0';
if(num<0||num>9) break;
string t = Phone[num];
if (t.length() == 0) continue;
for (int k = 0;k < t.length(); k++) {
for (int j = 0; j < res.size(); j++) {
temp.push_back(res[j]+t[k]);
}
}
res.swap(temp);
temp.clear();
}
return res;
}
};