Problem
Analysis Process
How many options do we have when we do the first step? Take “25525511135” for example
pick “2” for the first segment
pick “25” for the first segment
pick “255” for the first segment
There are three options. After you make your choice, you are faced with three options: cut out a piece of length for a second piece
This will branch down like a tree, and we’ll use the DFS to go through all the choices, and backtrace
Generate four valid fragments and use up the characters of the IP string
When the traversal node satisfies this condition, it means that a valid combination has been generated and 4 valid fragments have been generated by pushing into the result array, but not using all the characters, so it does not recurse down, directly returns, and then backtrace
Code
golang
var result []string
func restoreIpAddresses(s string) []string {
if len(s) < 4 || len(s) > 12 {
return nil
}
result = []string{
}
track := make([]string, 0)
backtrack(s, track, 1)
return result
}
func backtrack(s string, track []string, key int