Problem
Problem page: https://leetcode.com/problems/restore-ip-addresses/
Topics: Backtracking, String
Difficulty: Medium
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given"25525511135",return
["255.255.11.135", "255.255.111.35"]. (Order does not matter)
Analysis
(Could I solve this one with DP???)
Search, recursion, pruning.
The pruning conditions are: 1. No field can have a value greater than 255; 2. There must be exactly 4 fields; 3. A field with length >=2 can't start with 0. So the logic goes like this:
- If the current character isn't the last one
- If appending the current character to the current field (num) would give a value no greater than 255
- If the number of dots so far (fields) is less than 3, I can try adding a dot to the prefix (prefix) and starting a new field with the current character
- If the current field isn't 0, I can try appending the character to it
2 Otherwise, check whether there are fewer than 3 dots so far. If so, I can try adding a dot to the prefix (prefix) and starting a new field with the current character
- Otherwise, this branch fails
- If appending the current character to the current field (num) would give a value no greater than 255
- If the current character is the last one
- If there are already three dots, the current field isn't 0, and appending the current character would give a value no greater than 255, I can try appending it
- Otherwise, if there are already two dots, end the current field with a dot and use the current character as the last field to get a solution
- Otherwise, this branch fails
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-restore-ip-addresses/
