93.复原IP地址
题目链接/文章讲解:链接地址
视频讲解:链接地址
class Solution {
private:
vector<string> result;
void back_tracking(string& s, int startIndex, int pointNum) {
//结束条件
if (pointNum == 3) {
if (isValid(s, startIndex, s.size() - 1)) {
result.push_back(s);
}
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (isValid(s, startIndex, i)) {
s.insert(s.begin() + i + 1, '.');
pointNum++;
back_tracking(s, i + 2, pointNum);// 插入了‘.’
pointNum--; // 回溯
s.erase(s.begin() + i + 1);
} else break;
}
}
bool isValid(const string& s, int start, int end) {
if (start > end) {
return false;
}
//首字母为0
if (s[start] == '0' && start != end) {
return false;
}
//非数字
int nums = 0;
for (int i = start; i <= end; i++) { // 这里是start
if (s[i] > '9' || s[i] < '0') {
return false;
}
nums = 10 * nums + (s[i] - '0');
if (nums > 255) {
return false;
}
}
return true;
}
public:
vector<string> restoreIpAddresses(string s) {
// if (s.size() < 4 || s.size() > 12) return result;
back_tracking(s, 0, 0);
return result;
}
};
78.子集
题目链接/文章讲解:链接地址
视频讲解:链接地址文章来源:https://www.toymoban.com/news/detail-667971.html
class Solution {
private:
vector<int> path;
vector<vector<int>> result;
void back_tracking(vector<int>& nums, int startIndex) {
result.push_back(path);
if (startIndex >= nums.size())
return;
for (int i = startIndex; i < nums.size(); i++) {
path.push_back(nums[i]);
back_tracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
back_tracking(nums, 0);
return result;
}
};
90.子集II
题目链接/文章讲解:链接地址
视频讲解:链接地址文章来源地址https://www.toymoban.com/news/detail-667971.html
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void back_tracking(vector<int>& nums, int startIndex, vector<bool>& used) {
result.push_back(path);
for (int i = startIndex; i < nums.size(); i++) {
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
continue;
}
path.push_back(nums[i]);
used[i] = true;
back_tracking(nums, i + 1, used);
used[i] = false;
path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
back_tracking(nums, 0, used);
return result;
}
};
到了这里,关于代码随想录23| 93.复原IP地址, 78.子集, 90.子集II的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!