93. 复原 IP 地址
class Solution {
public:
vector<string> res;
void backtracking(string& s,int startIndex,int pointSum){
if(pointSum==3){
if(ok(s,startIndex,s.size()-1)){
res.push_back(s);
} return;}
for(int i=startIndex;i<s.size();i++){
if(ok(s,startIndex,i)){
s.insert(i+1,".");
backtracking(s,i+2,pointSum+1);
s.erase(i+1,1);
}
else break;
}
}
bool ok(string s,int start,int end){
if(start>end)return 0;
if(s[start]=='0'&&start!=end)return 0;
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) { // 如果大于255了不合法
return false;
}
}
return 1;
}
vector<string> restoreIpAddresses(string s) {
if(s.size()<4||s.size()>12)return res;
backtracking(s,0,0);
return res;
}
};
思路还是分割,使用插入点和撤回点来递归,三个点之后返回条件。
78. 子集
子集的思路了,每个结点都收集
class Solution {
public:
vector<int> path;
vector<vector<int>> res;
void backtracking(vector<int>& nums,int startIndex){
res.push_back(path);
for(int i=startIndex;i<nums.size();i++){
path.push_back(nums[i]);
backtracking(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
backtracking(nums,0);
return res;
}
};
90. 子集 II
结合前面的去重和子集
class Solution {
public:
vector<int> path;
vector<vector<int>> res;
void backtracking(vector<int>& nums,int startIndex){
res.push_back(path);
for(int i=startIndex;i<nums.size();i++){
if(i!=startIndex&&nums[i-1]==nums[i])continue;
path.push_back(nums[i]);
backtracking(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
backtracking(nums,0);
return res;
}
};