原题链接
我的回溯函数返回的是分段方法,是一组四元向量。如[3,3,2,3]表示IP地址的点分十进制的4个数分别是3位数,3位数,2位数,3位数。主函数中再将其对应到具体的IP地址
class Solution {
public:
vector<int> pos;
vector<vector<int>> ansPos;
public:
int Num(char cArr[], int start, int end){
int ans = 0;
for(int i = start; i <= end; i++){
ans = ans * 10 + cArr[i] - '0';
}
return ans;
}
void IpAddresses(string s, int n){
int size = s.size();
char sArr[s.size() + 1];
strcpy(sArr, s.c_str());
if(n == 1 && Num(sArr,0, size - 1) <= 255 && size > 0) {
pos.push_back(size);
for(int i = 0; i < pos.size(); i++){
cout<< pos[i] << " ";
}
cout<<endl;
ansPos.push_back(pos);
pos.pop_back();
return;
}
if(n == 1) return;
if(size < n || size > n * 3) return;
for(int i = 1; i <= 3; i++){
if(size > i){
int num = Num(sArr, size - i, size - 1);
// cout<< num << endl;
if((num > 255)) break;
pos.push_back(i);
// cout<<"substr: "<< s.substr(0, size - i) << endl;
IpAddresses(s.substr(0, size - i), n - 1);
pos.pop_back();
}
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
char sS[s.size() + 1];
strcpy(sS, s.c_str());
int h = 0;
IpAddresses(s, 4);
bool throwOut = false;
for(int i = 0; i < ansPos.size(); i++){
string oneAns;
for(int j = 3; j >= 0; j--){
for(int n = 0; n < ansPos[i][j]; n++){
oneAns.append(to_string(sS[h++] - '0'));
if(n == 0 && ansPos[i][j] > 1 && sS[h - 1] == '0') throwOut = true;
}
if(j != 0) oneAns.append(".");
}
ans.push_back(oneAns);
if(throwOut) ans.pop_back();
h = 0;
throwOut = false;
}
return ans;
}
};