"One Day together Leetcode" #93. Restore IP Addresses

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.