Program to generate all possible valid IP addresses from given string | Set 2 | Function to get all the valid ip - addresses ; If index greater than givenString size and we have four block ; Remove the last dot ; Add ip - address to the results ; To add one index to ip - address ; Select one digit and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove two index ( one for the digit and other for the dot ) from the end ; Select two consecutive digits and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove three index from the end ; Select three consecutive digits and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove four index from the end ; Driver code ; Fill result vector with all valid ip - addresses ; Print all the generated ip - addresses
def GetAllValidIpAddress ( result , givenString , index , count , ipAddress ) : NEW_LINE INDENT if ( len ( givenString ) == index and count == 4 ) : NEW_LINE INDENT ipAddress . pop ( ) ; NEW_LINE result . append ( ipAddress ) ; NEW_LINE return ; NEW_LINE DEDENT if ( len ( givenString ) < index + 1 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ipAddress = ( ipAddress + givenString [ index : index + 1 ] + [ ' . ' ] ) ; NEW_LINE GetAllValidIpAddress ( result , givenString , index + 1 , count + 1 , ipAddress ) ; NEW_LINE ipAddress = ipAddress [ : - 2 ] ; NEW_LINE if ( len ( givenString ) < index + 2 or givenString [ index ] == '0' ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ipAddress = ipAddress + givenString [ index : index + 2 ] + [ ' . ' ] ; NEW_LINE GetAllValidIpAddress ( result , givenString , index + 2 , count + 1 , ipAddress ) ; NEW_LINE ipAddress = ipAddress [ : - 3 ] ; NEW_LINE if ( len ( givenString ) < index + 3 or int ( " " . join ( givenString [ index : index + 3 ] ) ) > 255 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ipAddress += givenString [ index : index + 3 ] + [ ' . ' ] ; NEW_LINE GetAllValidIpAddress ( result , givenString , index + 3 , count + 1 , ipAddress ) ; NEW_LINE ipAddress = ipAddress [ : - 4 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT givenString = list ( "25525511135" ) ; NEW_LINE result = [ ] ; NEW_LINE GetAllValidIpAddress ( result , givenString , 0 , 0 , [ ] ) ; NEW_LINE for i in range ( len ( result ) ) : NEW_LINE INDENT print ( " " . join ( result [ i ] ) ) ; NEW_LINE DEDENT DEDENT