代码随想录算法训练营第二十八天 | 93.复原IP地址
93.复原IP地址
class Solution {
private:
vector<string> ip;
vector<string> result;
public:
vector<string> restoreIpAddresses(string s) {
backtracking(s, 0);
return result;
}
void backtracking(const string& s, int startIndex) {
if(startIndex == s.size()) {
string res = "";
int count = 0;
for(int i = 0; i < ip.size(); ++i) {
res += ip[i];
if(i != ip.size() - 1) {
res += ".";
count++;
}
}
if(count != 3) return ;
result.push_back(res);
return ;
}
for(int i = startIndex; i < s.size(); ++i) {
if(isValid(s, startIndex, i)) {
ip.push_back(s.substr(startIndex, i - startIndex + 1));
} else continue;
backtracking(s, i + 1);
ip.pop_back();
}
}
bool isValid(const string& s, int start, int end) {
// 有前导0不合法
if(s[start] == '0' && start != end) return false;
// 如果不在0~255之间则不合法
int dig = 0;
for(int i = start; i <= end; ++i) {
int num = s[i] - '0';
dig = dig * 10 + num;
if(dig < 0 || dig > 255) return false;
}
if(dig < 0 || dig > 255) return false;
return true;
}
};
78.子集
关键:每一层递归都应收集结果
class Solution {
private:
vector<int> sub;
vector<vector<int>> result;
public:
vector<vector<int>> subsets(vector<int>& nums) {
backtracking(nums, 0);
return result;
}
void backtracking(vector<int>& nums, int startIndex) {
result.push_back(sub);
if(sub.size() == nums.size()) {
return;
}
for(int i = startIndex; i < nums.size(); ++i) {
sub.push_back(nums[i]);
backtracking(nums, i + 1);
sub.pop_back();
}
}
};
90.子集II
class Solution {
private:
vector<int> sub;
vector<vector<int>> result;
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return result;
}
void backtracking(vector<int>& nums, int startIndex) {
result.push_back(sub);
for(int i = startIndex; i < nums.size(); ++i) {
if(i > startIndex && nums[i] == nums[i - 1]) continue;
sub.push_back(nums[i]);
backtracking(nums, i + 1);
sub.pop_back();
}
}
};