1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Solution { public: vector<string> result;
bool isValid(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 backtracing(string& s, int startIndex, int pointNum){ if(pointNum == 3){ if(isValid(s, startIndex, s.size() - 1)){ result.push_back(s); } return; }
for(int i = startIndex; i < s.size();i++){ if(isValid(s, startIndex, i)){ s.insert(s.begin() + i + 1, '.'); pointNum += 1; backtracing(s, i + 2, pointNum); pointNum -= 1; s.erase(s.begin() + i + 1); }else{ break; } } }
vector<string> restoreIpAddresses(string s) { result.clear(); backtracing(s, 0, 0); return result; } };
|