1 class Solution { 2 public: 3 vector<string> ret; 4 string src; 5 int len; 6 unordered_set<string> added; 7 vector<string> restoreIpAddresses(string s) { 8 if ( s.empty() ) return ret; 9 src = s; 10 len = src.size(); 11 backTrack(0,0, ""); 12 return ret; 13 } 14 15 void backTrack(int pos, int dot_cnt, string substr) { 16 if ( dot_cnt > 4 ) return; 17 if ( pos >= len && dot_cnt == 4 ) { 18 substr.pop_back(); 19 if ( added.find(substr) == added.end() ) { 20 ret.push_back( substr ); 21 added.insert( substr ); 22 } 23 return; 24 } 25 char buffer[16]; 26 int tx = len - pos > 3 ? 3 : len - pos; 27 for ( int i = 1; i <= tx; i++ ) { 28 string temp = src.substr( pos, i ); 29 int number = atoi( temp.c_str() ); 30 sprintf( buffer, "%d", number ); 31 string str(buffer); 32 if ( str != temp ) continue; 33 string newsub = substr + temp + "."; 34 if ( number >= 0 && number <= 255 ) { 35 backTrack( pos + i, dot_cnt + 1, newsub ); 36 } 37 } 38 } 39 };