Problem
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
1 |
|
Explanation
-
We can use recursion to solve this problem. We create a helper function that has 4 parameters: input string, result, current string, field. The valid ip address has totoal of 4 fields, for example,
field1.field2.field3.field4
. -
The idea is we first pull out one character from the input string, and check if it’s a valid field, if it is valid field, then we recursivly call the helper function with the updated parameter: updated sub inputString, result, currentString is the character we pull out, field+1. Similarlly, we can pull out two characters to check if it’s a valid field and recursivly call the helper function; we can also pull out three characters and recursivly call the helper function.
-
We will return if the field is 4 and the string has no length.
Solution
1 |
|