Released: 21:26:11, September 18, 2021
Problem description and examples
Given a string containing only numbers to represent an IP address, return all valid IP addresses that may be obtained from s. You can return answers in any order.
A valid IP address consists of exactly four integers (each integer is between 0 and 255 and cannot contain a leading 0). Integers are separated by '.'.
For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192 firstname.lastname@example.org ”Is an invalid IP address.
Input: s = "25525511135"
Output: [255.255.11.135 "," 255.255.111.35 "]
Input: s = "0000"
Input: s = "1111"
Input: s = "010010"
Output: ["0.10.0.10", "0.100.1.0"]
Input: s = "101023"
Output: ["220.127.116.11", "18.104.22.168", "10.1.0.23", "10.10.2.3", "22.214.171.124"]
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.
0 <= s.length <= 3000
s consists of numbers only
My solution (backtracking)
This should be the second topic about backtracking I met in LeetCode. I wrote a related topic explanation blog before:
In my opinion, backtracking is actually an application of recursion, which is often used in some situations where all possible conditions need to be enumerated. The difference between backtracking and general recursion is the so-called "backtracking" operation, that is, when one layer of recursion is completed, some variables in the program (these variables are often global) are restored to the state before recursion. The typical structure of backtracking operation is as follows:
let globalVar; let globalVar2; ... globalVar2++; operateA(); // Before operateA, the status of globalVar is X; After operateA, the state of globalVar changes to Y backtracking(params); operateB(); // Before operateB, the status of globalVar is Y; After operateB, the state of globalVar returns to X globalVar2--; ...
In other words, the operation effects of operateA() and operateB() just offset each other. For example, the push() and pop() methods of arrays. This is the quintessence of the backtracking algorithm: restoring the state before recursion.
Please refer to the notes below for detailed explanation:
Update: July 29, 2021 18:43:21
Because I consider the ownership of copyright, I won't paste the specific code in the [official solution], which can be viewed in the link below.
Update: 21:35:40, September 18, 2021
reference resources: Restore IP address - restore IP address - LeetCode
[end of update]
Update: 21:34:22, September 18, 2021
reference resources: [algorithm LeetCode] 46. Full Permutation (initial experience of backtracking algorithm)_ Lai nianan's blog - CSDN blog