今日记录
93.复原IP地址
class Solution {
private:
vector<string> result;
void backtracking(string s, int index, int pointNum) {
if (pointNum == 3) {
if (isValid(s, index, s.size() - 1)) {
result.push_back(s);
}
return;
}
for (int i = index; i < s.size(); i++) {
if (isValid(s, index, i)) {
s.insert(s.begin() + i + 1, '.');
pointNum++;
backtracking(s, i + 2, pointNum);
pointNum--;
s.erase(s.begin() + i + 1);
} else
break;
}
}
bool isValid(string s, int start, int end) {
if (start > end) {
return false;
}
if (s[start] == '0' && start != end) {
return false;
}
int num = 0;
for (int i = start; i <= end; i++) {
if (s[i] > '9' || s[i] < '0') {
return false;
}
num = num * 10 + (s[i] - '0');
if (num > 255) {
return false;
}
}
return true;
}
public:
vector<string> restoreIpAddresses(string s) {
result.clear();
if (s.size() < 4 || s.size() > 12)
return result;
backtracking(s, 0, 0);
return result;
}
};
78.子集
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int index) {
result.push_back(path);
if (index >= nums.size()) {
return;
}
for (int i = index; i < nums.size(); i++) {
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};
90.子集Ⅱ
重点在于去重的思路:
同一树层不能重复读取,同一树枝可以重复选取
判断方法:
if (i > index && nums[i] == nums[i - 1]) {
continue;
}
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int index) {
result.push_back(path);
for (int i = index; i < nums.size(); i++) {
if (i > index && 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) {
result.clear();
path.clear();
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return result;
}
};
总结
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 代码随想录算法训练营第24天 | 第七章 回溯算法part03
发表评论 取消回复