题目: 传送门
题意:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 “任意顺序” 返回。
代码:
#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
string mp[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string>ans;
queue<string>p;
for (int i = 0; i < digits.size(); i++) {
int x = digits[i]-'0';
int len = p.size();
if (len == 0) {
for (int k = 0; k < mp[x].size(); k++) {
string str1;
str1.append(1,mp[x][k]);
p.push(str1);
}
}
for (int j = 0; j < len; j++) {
string str;
str = p.front();
p.pop();
for (int k = 0; k < mp[x].size(); k++) {
string str1 = str;
str1.append(1 , mp[x][k]);
p.push(str1);
}
}
}
while (p.size()) {
ans.push_back(p.front());
p.pop();
}
return ans;
}
};
int main() {
string str;
while (1) {
cin >> str;
vector<string>p;
Solution s;
p = s.letterCombinations(str);
for (int i = 0; i < p.size(); i++)
cout << p[i] << " ";
cout << endl;
}
return 0;
}
可以使用队列,根据队列的特性,然后完成对所有情况的列举。如果把一个字符插入字符串,使用append()函数来完成对字符串的更新。
注重容器的使用。
使用vector容器:
#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
string mp[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string>ans;
for (int i = 0; i < digits.size(); i++) {
int x = digits[i] - '0';
int len = ans.size();
if (len == 0) {
for (int k = 0; k < mp[x].size(); k++) {
string str;
str.append(1, mp[x][k]);
ans.push_back(str);
}
}
else {
for (int i = 0; i < len; i++) {
string str = ans[0];
for (int k = 0; k < mp[x].size(); k++) {
string str1=str;
str1.append(1, mp[x][k]);
ans.push_back(str1);
}
vector< string >::iterator k = ans.begin();///删除第一个元素
ans.erase(k);///删除指定元素
}
}
}
return ans;
}
};
int main() {
string str;
while (1) {
cin >> str;
vector<string>p;
Solution s;
p = s.letterCombinations(str);
for (int i = 0; i < p.size(); i++)
cout << p[i] << " ";
cout << endl;
}
return 0;
}
使用dfs深搜:
#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
string mp[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };
class Solution {
public:
vector<string>ans;
string str;
void dfs(int x,string digits) {
if (x == digits.size()) {
ans.push_back(str);
return;
}
int k = digits[x] - '0';
for (int i = 0; i < mp[k].size(); i++) {
string str1 = str;
str.append(1, mp[k][i]);
dfs(x+1, digits);
str = str1;
}
return;
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0)
return ans;
dfs(0, digits);
return ans;
}
};
int main() {
string str;
while (1) {
cin >> str;
vector<string>p;
Solution s;
p = s.letterCombinations(str);
for (int i = 0; i < p.size(); i++)
cout << p[i] << " ";
cout << endl;
}
return 0;
}