LeetCode 17. Letter Combinations of a Phone Number
Solution1:我的答案
利用8皇后同样的方法,回溯+递归
时间复杂度
O(3n)
O
(
3
n
)
,空间复杂度
O(n)
O
(
n
)
1.1写的略复杂
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return vector<string>();
set<string> result; //自动避免重复
unordered_map<char, vector<string> > num = {{'2', {"a", "b", "c"}},
{'3', {"d", "e", "f"}},
{'4', {"g", "h", "i"}},
{'5', {"j", "k", "l"}},
{'6', {"m", "n", "o"}},
{'7', {"p", "q", "r", "s"}},
{'8', {"t", "u", "v"}},
{'9', {"w", "x", "y", "z"}}
};
string temp = "";
int start = 0;
Combinate(num, result, temp, digits, start);
return vector<string> (result.begin(), result.end());
}
void Combinate(unordered_map<char, vector<string>>& num,
set<string>& result, string temp, string& digits, int start) {
if (start == digits.size()) {
result.insert(temp);
return;
}
else {
for (int i = 0; i < num[digits[start]].size(); i++) {
temp = temp + num[digits[start]][i];
Combinate(num, result, temp, digits, start + 1);
temp.erase(temp.size() - 1);
}
}
}
};
1.2代码略微简化一点
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return vector<string>();
set<string> result; //自动避免重复
vector<string> num = {"abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"};
string temp = "";
int start = 0;
Combinate(num, result, temp, digits, start);
return vector<string> (result.begin(), result.end());
}
void Combinate(vector<string>& num, set<string>& result,
string temp, string& digits, int start) {
if (start == digits.size()) {
result.insert(temp);
return;
} else {
for (int i = 0; i < num[digits[start] - '2'].size(); i++) {
temp = temp + num[digits[start] - '2'][i];
Combinate(num, result, temp, digits, start + 1);
temp.erase(temp.size() - 1);
}
}
}
};
几个重要注意事项
1.C++的string对象利用下标操作符“[]”得到的数据类型是char,要初始化char类型的数据要用单引号修饰单个字符;
2.编译错误stray ‘\343’ in program解决办法
这种错误是由于代码中含有中文的引号or其他的全脚符号引起的,而小编遇到的是由中文空格引起的,不易发现
参考链接:https://blog.csdn.net/u012349696/article/details/51043830