class Solution {
public:
vector<string> res;
bool isVaild(const 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;
}
void backtracking(string &s,int startIndex,int pointNum){
if(pointNum==3)
{
//判断第四段是否符合要求
if(isVaild(s,startIndex,s.size()-1))
res.push_back(s);
return;
}
for(int i=startIndex;i<s.size();i++){
if(isVaild(s,startIndex,i)){
s.insert(s.begin()+i+1,'.');
backtracking(s,i+2,pointNum+1);
s.erase(s.begin()+i+1);
}else{
break;//说明所有的都不合法了直接break
}
}
}
vector<string> restoreIpAddresses(string s) {
backtracking(s,0,0);
return res;
}
};
思路:
递归遍历 pointNum=3为终止条件 isValue判断是不是符合要求闭区间得证
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums,int startIndex){
if(startIndex==nums.size()){
res.push_back(path);
return;
}
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;
}
};
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums,int startIndex,vector<bool> is){
if(startIndex==nums.size()){
res.push_back(path);
return;
}
res.push_back(path);
for(int i=startIndex;i<nums.size();i++){
//false代表是同一树层 现在属于前面的真子集一定被遍历过了 直接continue
if(i>0&&nums[i]==nums[i-1]&&is[i-1]==false){
continue;
}
path.push_back(nums[i]);
is[i]=true;
backtracking(nums,i+1,is);
is[i]=false;
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<bool> is(nums.size(),false);
sort(nums.begin(),nums.end());
backtracking(nums,0,is);
return res;
}
};