93. 复原 IP 地址
class Solution {
public:
vector<vector<string>> result;
vector<string> path;
bool check(string& sub){
if(sub.length()>1&&sub[0]=='0')
return false;
try{
if(stoi(sub)>255)
return false;
}
catch(...){
return false;
}
return true;
}
void dfs(string s, int startIdx){
if(path.size()==4){
if(startIdx==s.length())
result.push_back(path);
return;
}
for(int endIdx=startIdx+1; endIdx<=startIdx+3&&endIdx<=s.length(); endIdx++){
string sub=s.substr(startIdx,endIdx-startIdx);
if(check(sub)){
path.push_back(sub);
dfs(s,endIdx);
path.pop_back();
}
}
}
string join(vector<string> path){
string ans=path[0];
for(int i=1;i<path.size();i++){
ans+="."+path[i];
}
return ans;
}
vector<string> restoreIpAddresses(string s) {
dfs(s,0);
vector<string> res;
for(auto& path:result)
res.push_back(join(path));
return res;
}
};
ip最多4段,所以根据path.size()终止回溯,此时如果字符串被切割到末尾,则是一个有效的分割。另外,每一段最大255,所以子串长度最大为3,据此可以进行剪枝。
78. 子集
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void dfs(vector<int>& nums, int startIdx){
if(path.size()==nums.size()){
return;
}
for(int i=startIdx; i<nums.size(); i++){
path.push_back(nums[i]);
result.push_back(path);
dfs(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
result.push_back({});
dfs(nums,0);
return result;
}
};
遍历的过程收集结果即可。
90. 子集 II
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
void dfs(vector<int>& nums, int startIdx){
if(path.size()==nums.size()){
return;
}
for(int i=startIdx; i<nums.size(); i++){
path.push_back(nums[i]);
result.push_back(path);
dfs(nums,i+1);
path.pop_back();
while(i+1<nums.size()&&nums[i+1]==nums[i])
i++;
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
result.push_back({});
sort(nums.begin(),nums.end());
dfs(nums,0);
return result;
}
};
回溯同层去重。
标签:24,return,nums,int,随想录,vector,result,回溯,path From: https://blog.csdn.net/jiyisuifeng1991/article/details/141981129