[algorithm LeetCode] 93. Restore IP address (backtracking; recursion)

Posted by timbuckthree on Sun, 19 Sep 2021 09:49:09 +0200

93. Restore IP address LeetCode

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 168@1.1 ”Is an invalid IP address.

Example 1:
Input: s = "25525511135"
Output: [255.255.11.135 "," 255.255.111.35 "]

Example 2:
Input: s = "0000"
Output: ["0.0.0.0"]

Example 3:
Input: s = "1111"
Output: ["1.1.1.1"]

Example 4:
Input: s = "010010"
Output: ["0.10.0.10", "0.100.1.0"]

Example 5:
Input: s = "101023"
Output: ["1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3", "101.0.2.3"]

Source: LeetCode
Link: https://leetcode-cn.com/problems/restore-ip-addresses
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Tips:
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:

reference resources: [algorithm LeetCode] 46. Full Permutation (initial experience of backtracking algorithm)_ Lai nianan's blog - CSDN blog

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:

/**
 * @param {string} s
 * @return {string[]}
 */
var restoreIpAddresses = function (s) {
  if (s.length < 4 || s.length > 12) {
    return [];
  }
  let results = [];
  let ip = [];
  backtracking(s, 0);
  return results;

  function backtracking(str, start) {
    // The performance can also be optimized by adding the following if judgment
    if(ip.length > 4) {
      return;
    }
    if (start === str.length) {
      if (ip.length === 4) {
        results.push(ip.join('.'));
      }
      return;
    }
    for (let i = start; i < str.length; i++) {
      let segment = str.substring(start, i + 1);
      if (!isValidSegment(segment)) {
        break;
      }
      ip.push(segment);
      backtracking(str, i + 1);
      ip.pop();
    }
  }
  function isValidSegment(str) {
    if (!str || str.length > 3) {
      return false;
    }
    if (str[0] === '0') {
      return str.length > 1 ? false : true;
    }
    return Number(str) <= 255 ? true : false;
  }
};


Submit records
 Execution result: passed
147 / 147 Pass test cases
 Execution time: 76 ms, At all JavaScript Defeated 67 in submission.63%User
 Memory consumption: 39.3 MB, At all JavaScript Defeated 55 in submission.32%User
 Time: 2021/09/18 21:35

Official 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]

Relevant reference

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
reference resources: String.prototype.substring() - JavaScript | MDN

Topics: Javascript Algorithm leetcode