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)
Test Instructions:
Given a string that contains only a number, returns all valid IP addresses that comprise the string.
Like what:
Given "25525511135" ,
返回["255.255.11.135", "255.255.111.35"]. (Not in order)
Algorithm Analysis:
* IP is divided into 4 segments, each of which has a value of 0-255, which means that each bit may be 1 bits, 2 digits or 3 digits
* Therefore for a given number string, we need to determine the values in 4 positions, each position has three possible digits to value,
* Therefore, a total of possible IP segment partitioning schemes in 3^4=81 are considered.
solve sub-problems with cyclic recursion. For each segment, a maximum of 3 bits is at least 1 bits, so you can loop 3 times at each level to try to fill in the segments. Because the IP address up to 4 segments, when the number of layers is 3 to indicate that you have already tried to fill out 3 segments, then the remaining number of fields to the end. the process is to ensure that the number of fills is legal, the final stitching of the remaining number is also legal.
Note that the beginning if it is 0 to special treatment, if the beginning is 0, to determine whether the entire string is 0, not the character is illegal. Because the 001,01 is wrong.
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution {public arraylist<string> restoreipaddresses (String s) {Arraylist<str ing> res = new arraylist<string> (); String item = new string (); if (s.length () <4| | S.length () >12) return res; DFS (s, 0, item, RES); return res; public void Dfs (string s, int start, string item, arraylist<string> res) {if (start = = 3 & amp;& IsValid (s)) {Res.add (item + s); Return } for (int i=0; i<3 && i<s.length ()-1; i++) {String substr = s.substring (0,i+1) ; if (IsValid (substr)) Dfs (s.substring (i+1, S.length ()), start+1, item + substr + '. ', res); }} public Boolean isValid (String s) {if (S.charat (0) = = ' 0 ') return s.equals ("0"); int Num = Integer.parseint (s); if (num <= 255 && num > 0) return true; else return false; }}</span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Restore IP Addresses