One Day together Leetcode
This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source
(i) Title
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)
(ii) Problem solving
Topic: Given a string of characters, determine how many valid IP addresses can be composed
You need to pay attention to invalid IP, such as 00,010, etc in solving process
Problem-solving ideas: The use of backtracking, IP has four levels, respectively, to determine whether each level is effective, in turn recursive, to the final judgment can constitute a valid IP, no back to the previous level to continue recursion. Detailed ideas See code comments
classSolution { Public: vector<string>Restoreipaddresses (strings) { vector<string>Retstringip Dfsrestoreip (S,ip,0,0, ret);returnRet }voidDFSRESTOREIP (string& S,stringIpintCount,intI vector<string>&ret) {if(count==4)//Count to 4 indicates an IP address{if(I==s.length ()) {Ip.erase (Ip.end ()-1);//Remove the last '. 'Ret.push_back (IP); }return; }intnum =0; for(intj = i; J < S.length (); J + +) {Ip+=s[j]; num = num*Ten+ (s[j]-' 0 ');if(num>0&&s[i]==' 0 ')return;//Remove invalid IPs such as ' 01 ', ' 010 ' if(num==0&&j-i>=1)return;//Remove invalid IPs such as ' 00 ' if(num< the) {ip+='. ';//Plus. Representative to the next levelDfsrestoreip (s,ip,count+1, j+1, ret); Ip.erase (Ip.end ()-1);//Back to the previous level}Else return; } }};
"One Day together Leetcode" #93. Restore IP Addresses