Day 28 回溯算法
93. 复原IP地址
我的做法有点奇怪,还是参考一下代码随想录的做法吧
class Solution {
vector<string> rst;
vector<string> path;
int str2num(const string &s)
{
auto iter = s.begin();
int rst = 0;
while (iter != s.end())
{
rst = rst * 10 + (*iter - '0');
iter++;
}
return rst;
}
void backtracking(const string &s, int idx)
{
if (idx == s.size() && path.size() == 4)
{
string tmp;
for (int i = 0; i < 4; i++)
{
if (i > 0)
{
tmp += ".";
}
tmp += path[i];
}
rst.push_back(tmp);
}
else if (idx > s.size() || path.size() > 4) // 剪枝
{
return;
}
for (int i = 1; i <= 3; ++i)
{
string tmp = s.substr(idx, i);
int num = str2num(tmp);
if (num > 255) continue;
path.push_back(tmp);
backtracking(s, idx + i);
path.pop_back();
if (s[idx] == '0')
{
break;
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
if (s.size() < 4 || s.size() > 12) // 剪枝
{
return {};
}
rst.clear();
path.clear();
backtracking(s, 0);
return rst;
}
};
73. 子集
class Solution {
vector<vector<int>> rst;
vector<int> path;
void backtracking(const vector<int> &nums, int idx)
{
rst.push_back(path);
if (idx >= nums.size())
{
return;
}
for (int i = idx; i < nums.size(); ++i)
{
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
rst.clear();
path.clear();
backtracking(nums, 0);
return rst;
}
};
90. 子集II
涉及到去重,可别忘了排序文章来源:https://www.toymoban.com/news/detail-603054.html
不然去重的效果没法实现文章来源地址https://www.toymoban.com/news/detail-603054.html
class Solution {
vector<vector<int>> rst;
vector<int> path;
void backtracking(const vector<int> &nums, int idx)
{
rst.push_back(path);
if (idx >= nums.size())
{
return;
}
for (int i = idx; i < nums.size(); ++i)
{
if (i > idx && nums[i] == nums[i - 1])
{
continue;
}
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
rst.clear();
path.clear();
// 别忘了排序,因为要去重,所以要排序
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return rst;
}
};
到了这里,关于算法刷题Day 28 复原IP地址+子集+子集II的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!