Given a string containing only digits, restore it is returning all possible valid IP address combinations.
For example:
Given "25525511135" ,
Return ["255.255.11.135", "255.255.111.35"] . (Order does not matter)
A typical DFS, but the point is to note what the real IP address is, the code is as follows:
1 classSolution {2 Public:3vector<string> restoreipaddresses (strings) {4 if(S.size () > A)returnret;5DFS (S,0,0);6 returnret;7 }8 9 BOOLCheckstring&s)Ten { One if(s.size () = =1) A return "0"<= s && s <="9"; - Else if(s.size () = =2) - return "Ten"<= s && s <=" About"; the Else if(s.size () = =3) - return " -"<= s && s <="255"; - Else - return false; + } - + voidDfsConst string& S,intStartintnth) A { at if(Nth = =4&& Start! =s.size ()) - return; - Else if(Nth = =4&& start = =s.size ()) { - stringTMP =""; - for(inti =0; I <3; ++i) { -TMP + =Tmpres[i]; inTMP + ="."; - } toTMP + = tmpres[3];//for the sake of formatting + Ret.push_back (TMP); - } the Else * for(inti =1; I <4; ++i) { $ if(Start + i <=s.size ()) {Panax Notoginseng stringTMP =s.substr (start, i); - if(check (TMP)) { the Tmpres.push_back (TMP); +DFS (s, start + I, Nth +1); A Tmpres.pop_back (); the } + } - } $ } $ - Private: -vector<string>Tmpres; thevector<string>ret; -};
It's a little messy, forgive me.
Leetcode oj:restore IP Addresses (storage IP address)