题意
一段数字,求出其所对应的手机键盘上的字母组合
思路
解法一:
组合的个数为除了0和1之外的其他数字代表的字母数相乘,例如:"23" = 9
种情况,所以可得:
sum=∑n−1i=0cnt[i]
,其中
cnt[i]
为数字对应字母数
所以说,事先将组合数求出,然后可以发现,第一个数所对应的字符串的第一个字符所对应的组合有
sum/cnt[0]
,第二个数所对应的字符串的第一个字符所对应的组合有
sumcnt[0]∗cnt[1]
,由此可推出,每个数字对应的字符,在一轮中出现次数为
sum∑ij=0cnt[j]
,例如:
输入:”22”
计算的共有9种情况第一轮过后为
“a”,”a”,”a”,”b”,”b”,”b”,”c”,”c”,”c”
第二轮过后为
“aa”,”ab”,”ac”,”ba”,”bb”,”bc”,”ca”,”cb”,”cc”
注意中间的循环次数,即轮数
代码
class Solution {
public:
vector<string> letterCombinations(string digits) {
int len = digits.length();
string nums[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
int cnt = 1;
vector<string>ans;
for(int i = 0; i < len;i++){
if(digits[i] < '0' || digits[i] > '9') continue;
if(digits[i] == '0' || digits[i] == '1') continue;
cnt *= nums[digits[i] - '0'].length();
}
if(cnt == 1){
return ans;
}
for(int i = 0; i < cnt;i++){
ans.push_back("");
}
int sum = cnt;
for(int i = 0 ; i < len;i++){
if(digits[i] < '0' || digits[i] > '9') continue;
if(digits[i] == '0' || digits[i] == '1') continue;
string nowStr = nums[digits[i] - '0'];
int s = nowStr.length();
vector<string>tempAns;
int loc = 0;
int r = sum / cnt;
cnt /= s;
for(int id = 0; id < r; id++){
for(int j = 0; j < s;j++){
for(int k = 0; k < cnt; k++){
tempAns.push_back(ans[loc++] + nowStr[j]);
}
}
}
ans = tempAns;
}
return ans;
}
};