반응형
<Leetcode Solution>
17.Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Constraints:
- 0 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.size() == 0){
return;
}
map<char,string> m;
m['2'] = "abc";
m['3'] = "def";
m['4'] = "ghi";
m['5'] = "jkl";
m['6'] = "mno";
m['7'] = "pqrs";
m['8'] = "tuv";
m['9'] = "wxyz";
int size = 1;
for(int i=0; i<digits.size(); i++){
size*=m[digits[i]].size();
}
int itr = size;
vector<string> ans(size,"");
for(int i=0; i<digits.size(); i++){
int temp = i,k=0, count=0;
itr /= m[digits[i]].size();
if(itr == 0){
itr = 1;
}
for(int j=0; j<size; j++){
if(count == itr){
k++;
if(k == m[digits[i]].size()) {
k = 0;
}
count = 0;
}
ans[j] += m[digits[i]][k];
count++;
}
}
return ans;
}
};
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode.412][easy] Fizz Buzz (0) | 2021.10.30 |
---|---|
[LeetCode.454][middle] 4Sum II (0) | 2021.10.28 |