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)
Hide TagsBacktracking String
Idea: Dfs,backtrace,ip can only be composed of 3 digits, 1, 2, 3 each attempt, 2 bit when the first bit can not be 0, 3 bits is 0~255
classSolution {Vector<string>M_res; Vector<string>m_str; Public: voidDfsintDepstrings) {//Printvector (m_str); if(M_str.size () >4) return; if(m_str.size () = =4&& DEP <s.size ())return; if(DEP = =s.size ()) { if(m_str.size () = =4) { stringTmpstr; for(inti =0; I <3; i++) {Tmpstr+ = (M_str[i] +"."); } tmpstr+ = m_str[3]; M_res.push_back (TMPSTR); } return; } for(inti =1; I <=3; i++) { if((dep+i-1) >=s.size ()) Break; if(i = =2) { if(S[DEP] = ='0') Break; } Else if(i = =3) { if(S[DEP] = ='1'||(S[DEP]=='2'&& (s[dep+1] <='4'|| (s[dep+1] =='5'&& s[dep+2] <'6')))) ; Else Break; } m_str.push_back (S.substr (DEP, i)); DFS (DEP+I, s); M_str.pop_back (); }} vector<string> restoreipaddresses (strings) {m_res.clear (); M_str.clear (); DFS (0, s); returnM_res; }};
[Leetcode] Restore IP Addresses