代码随想录算法训练营第三十天
93.复原IP地址
题目链接:93.复原IP地址
class Solution {
public:
string st;
vector<string> result;
int pointSum;
bool isIP(string s,int start,int end){
if(start>end)return false;
if(s[start]=='0'&&start!=end)return false;//判断0开头的数字非法
int num = 0;
for(int i = start;i<=end;i++){
if(s[i]<'0'||s[i]>'9')return false;
num=num*10+(s[i]-'0');
if(num>255)return false;//判断255以上的数字非法
}
return true;
}
void backtracking(int startIndex,string &s){
if(pointSum==3){
if (isIP(s, startIndex, s.size()-1)){//判断第四段是否合法
result.push_back(s);
}
return;
}
for(int i =startIndex;i<s.size();i++){
if(isIP(s, startIndex, i)){//判断当前字段是否合法
s.insert(s.begin()+i+1, '.');//在合法字段之后加.
pointSum+=1;
backtracking(i+2, s);//递归,因为加了.多一个字符所以要+2
pointSum-=1;//回溯
s.erase(s.begin()+i+1);
}else break;
}
}
vector<string> restoreIpAddresses(string s) {
backtracking(0, s);
return result;
}
};
78.子集
题目链接:78.子集
class Solution {
public:
vector<int> result;
vector<vector<int>> results;
void backtracking(vector<int>& nums,int startIndex){
results.push_back(result); //将所有结果放到结果集内
if(startIndex>=nums.size())return; //如果到数据集结尾就返回
for(int i = startIndex;i<nums.size();i++){
result.push_back(nums[i]);
backtracking(nums, i+1);
result.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
backtracking(nums, 0);
return results;
}
};
90.子集II
题目链接:90.子集II
class Solution {
public:
vector<int> result;
vector<vector<int>> results;
void backtracking(vector<int>& nums,int startIndex){
results.push_back(result);
if(startIndex>=nums.size())return;
for(int i = startIndex;i<nums.size();i++){
if(i>startIndex&&nums[i-1]==nums[i])continue;//先排序再去重,要跳过本层第一个数
result.push_back(nums[i]);
backtracking(nums, i+1);
result.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
backtracking(nums, 0);
return results;
}
};