第十七题:电话号码的字母组合
解题思路:这个题会让我想到hashmap,或者直接打表,然后找到后,遍历值,解出所有可能解。
遍历方式,可以采用回溯法(DFS),或者采用队列(BFS)。
回溯法代码:
void callBackStr(vector<string>& strs, const unordered_map<char, string>& phoneMap,
const string & digits, int index, string &str)
{
if (index == digits.length())
{
strs.push_back(str);
}
else
{
char digit = digits[index];
const string &letters = phoneMap.at(digit);
for (const char &letter : letters)
{
str.push_back(letter);
callBackStr(strs, phoneMap, digits, index + 1, str);
str.pop_back();
}
}
}
vector<string> letterCombinations(string digits)
{
vector<string> strs; //要返会的结果
if (digits.empty())
{
return strs;
}
unordered_map<char, string> phoneMap{
{'2',"abc"},
{'3',"def"},
{ '4', "ghi" },
{ '5', "jkl" },
{ '6', "mno" },
{ '7', "pqrs" },
{ '8', "tuv" },
{ '9', "wxyz" }
};
string str;
callBackStr(strs,phoneMap,digits,0,str);
return strs;
}
队列方式BFS:
//BFS 采用队列的方式
vector<string> letterCombinations2(string digits)
{
vector<string> strs; //要返会的结果
if (digits.empty())
{
return strs;
}
unordered_map<char, string> phoneMap{
{ '2',"abc" },
{ '3',"def" },
{ '4', "ghi" },
{ '5', "jkl" },
{ '6', "mno" },
{ '7', "pqrs" },
{ '8', "tuv" },
{ '9', "wxyz" }
};
//申请队列
queue<string> que;
for (int i =0; i< phoneMap[digits[0]].size(); ++i)
{
string str;
str.push_back(phoneMap[digits[0]][i]);
que.push(str);
}
string str1 = ""; //存储对头元素
for (int i = 1; i < digits.size(); ++i)
{
int length = que.size();
while (length --)
{
for (int j = 0; j < phoneMap[digits[i]].size(); j++)
{
str1 = que.front();
str1 = str1 + phoneMap[digits[i]][j];
que.push(str1);
}
que.pop();//
}
}
while (!que.empty())
{
strs.push_back(que.front());
que.pop();
}
return strs;
}
第十八题:四数之和
解题思路:这个题目跟3个数相加有一样的想法,采用双指针方法,在多下个下标,这样不断是改变,就是这么无聊,题目出的,就这样去写吧:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
int size = nums.size();
for (int a = 0; a < size - 3; ++a)
{
if (a > 0 && nums[a] == nums[a - 1])continue;
for (int b = a + 1; b < size - 2; ++b)//以下代码与三数之和一样的
{
if (b > a + 1 && nums[b] == nums[b - 1])continue;
int i = b + 1, j = size - 1;
while (i < j)
{
int sum = nums[a] + nums[b] + nums[i] + nums[j];
if (sum < target)
while (i < j&&nums[i] == nums[++i]);
else if (sum > target)
while (i < j&&nums[j] == nums[--j]);
else {
result.push_back(vector<int>{nums[a], nums[b], nums[i], nums[j]});
while (i < j&&nums[i] == nums[++i]);
while (i < j&&nums[j] == nums[--j]);
}
}
}
}
return result;
}
不知道为啥,题目写着写着就比较烦了,有的题目是相对重复的,代码也很无聊,时间全部用来写题了,感觉自己错了方向,以后还是少一点题目吧,一点一点来吧,主要是学到东西,而不是刷多少题。加油提高自己的思想吧。